JavaWEB’s JDBC connection database addition, deletion, modification and query

JavaWEB’s JDBC connection database addition, deletion, modification and query

Database operation based on Myeclipse (not importing the driver into tomcat) 1>Create a new java Web project. Right-click the project project new->folder and name it lib (used to store the jdbc driver) 2>Find the driver (mysql-connector-java-5.0.4-bin.jar) and import it into lib, rightkey Click driver->build path->add build path. If you see a file that looks like a milk bottle, it means the import is successful, that is, the database driver is now ready for use 3>Open mysql create database books; create table book(name varchar(15),id int); 4>Write a program to add, delete, modify and check (take the java program as an example, the writing in java web is similar) package com; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Scanner; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; import com.mysql.jdbc.ResultSet; public class test { public static void main(String[] args) throws ClassNotFoundException, SQLException { Insert1(123456,“pan”); //Query1(); } public static void Insert1(int id,String na) throws ClassNotFoundException, SQLException{ Connection cOnn=null; Class.forName(“com.mysql.jdbc.Driver”); cOnn=(Connection) DriverManager.getConnection(“jdbc:mysql://localhost:3306/book”,“root”,“123456” ); String sql=“insert into b(name,id)values(?,?)”; PreparedStatement pst=(PreparedStatement) conn.prepareStatement(sql); pst.setString(1,na); pst.setInt(2,id); pst.executeUpdate(); if(conn!=null){ conn.close(); } } public static void Query1() throws ClassNotFoundException, SQLException{ Connection cOnn=null; Class.forName(“com.mysql.jdbc.Driver”); cOnn=(Connection) DriverManager.getConnection(“jdbc:mysql://localhost:3306/book”,“root”,“123456” ); String sql=“select * from b”; PreparedStatement pst=(PreparedStatement) conn.prepareStatement(sql); ResultSet rs=(ResultSet) pst.executeQuery(); while(rs.next()){ int c=rs.getInt(2); String name=rs.getString(1); System.out.println(c+“,”+name+“,”); } if(conn!=null){ conn.close(); }…

Development notes: Java connection database addition, deletion, modification and query

Preface: This article is organized by the editor of Programming Notes#. It mainly introduces the knowledge related to Java connection database addition, deletion, modification and query. I hope it will be of certain reference value to you. 1 package org.test.com; 2 3 import java.sql.Connection; 4 import java.sql.Date; 5 import java.sql. DriverManager; 6 import java.sql.ResultSet; 7 import java.sql.Statement; 8 9 public class Database {10 public static void main(String[] args) {11 /*12 * There is a table named friends in SQL Server, as shown below, using JDBC programming to display the record information in the table. 13 * Column name data type14 * Name Varchar(50) 15 * Address Varchar(50) 16 * Phone Numeric 17 * Joining dateDatetime 18 * Salary Numeric19 */20 Statement state;21 int result;22 // Write the jdbc driver in the try-catch statement 23 try {24 Class.forName(“com.mysql.jdbc.Driver”);25 } catch (ClassNotFoundException e) {26 System.out.println(e);27 } 28 //Then perform database connection and operation in the try-catch statement29 try span> {30 //Connect to database31 String url = “jdbc:mysql://localhost:3306/mydatabases”;//?useUnicode=true&characterEncoding=utf832 String username = “root”;33 String password = “123456”;34 Connection cOnnection= DriverManager .getConnection(url, username, password);35 //Connection cOnnection= DriverManager.getConnection(“jdbc:mysql://localhost:3306/mydatabases”, “root”, “123456”);36 37 //Write data into the database38 String sql=”insert into friends values(‘ Luo Er’,’Shandong’,’15000000001′,’2019-12-11′,’80000′)”;39 state=connection .createStatement();40 result=state.executeUpdate(sql);41…

elasticsearchjava based on RestClientAPI addition, deletion, modification and query

RestClient class client 5 request methods public class EsRestClient { private static final String PUT = “PUT”;private static final String POST = “POST”;private static final String GET = “GET”;private static final String HEAD = “HEAD”;private static final String DELETE = “DELETE”;public static RestClient getClient(){return getClient(CommonResource.cloud_es_dm_ip, CommonResource.cloud_es_dm_rest_port);}public static RestClient getClient(String ip, Integer port){return RestClient.builder(new HttpHost(ip,port)).setMaxRetryTimeoutMillis(6000).build();}public static String sendGet(String ip,Integer port,String index,String type,String query){RestClient restClient = getClient(ip,port);String rs = null;try {HttpEntity entity = new NStringEntity(query, ContentType.APPLICATION_JSON);String endpoint = “/”+index+ “/”+type+“/_search”;if(StringUtils.isBlank(type)){endpoint = “/”+index+“/_search”;}Response response = restClient.performRequest(GET, endpoint, Collections.singletonMap(“pretty”, “true”),entity);rs = EntityUtils.toString(response.getEntity ());} catch (IOException e) {e.printStackTrace();}finally {close(restClient);}return rs; }public static String sendPost(List indexs,List types,String query){RestClient restClient = getClient();String rs = null;try {String index = StringUtils.join(indexs, “,”);String type = “/”;if(Objects.nonNull(types) && !types.isEmpty()){type += StringUtils.join(types, “,”)+“/”;}HttpEntity entity = new NStringEntity(query, ContentType.APPLICATION_JSON);String endpoint = “/”&index+type+“_search”;Response response &# 61; restClient.performRequest(POST, endpoint, Collections.singletonMap(“pretty”, “true”) ,entity);rs = EntityUtils.toString(response.getEntity());} catch (IOException e) {e.printStackTrace();}finally { close(restClient);}return rs;}public static String sendPut(String ip, int port,String index,String type,String id ,String data){RestClient restClient = getClient(ip,port);String rs = null;try {HttpEntity entity = new NStringEntity(data, ContentType.APPLICATION_JSON);String requestType = POST ;String endpoint =“/”+index+“/”+type;if( StringUtils.isNoneBlank(id)){requestType = PUT;endpoint = “/”+index&# 43;“/”+type+“/”+id;}Response response = restClient.performRequest(requestType, endpoint , Collections.singletonMap(“pretty”, “true”),entity);rs = EntityUtils.toString(response.getEntity());} catch (IOException e) {e.printStackTrace();}finally {close(restClient);}return rs;}public static String sendDelete(RestClient restClient,String…

Development notes: Java connection to Redis and redis addition, deletion, modification and query

Preface: This article is organized by the editor of Programming Notes#. It mainly introduces the knowledge related to the addition, deletion, modification and query of redis between Java and Redis. I hope it will be of certain reference value to you. 1. Create a new maven project. The project can be in the form of jar or war, and then import the correct dependencies 4.0.0 com. test redis 0.0.1-SNAPSHOT UTF-8 redis.clients jedis 2.5.0 junit junit 4.12 test org.apache.maven.plugins maven-compiler-plugin 2.0.2 1.8 1.8 2. Build a tool class to connect to the redis database package com.xiangjun.redis;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;public class RedisUtil {  //Server IP address private static String ADDR = “23.228.103.10”;  //Port private static int PORT = 6379; //Password private static String AUTH = “123456 “; //The maximum number of connections for the connection instance private static int MAX_ACTIVE = 1024 ;  //Control the maximum number of idle jedis in a pool. Instance, the default value is also 8. private static int MAX_IDLE = 200;  //The maximum time to wait for an available connection, in milliseconds. The default value is -1, which means it will never time out. If the waiting time is exceeded, JedisConnectionException will be thrown directly. private static int MAX_WAIT =…

javamysql addition, deletion, modification and query

First, establish a connection with mysql, load this class with Class.forName(), and then initialize it with a static method. DriverManager.getConnection gets the connection package analysis;import java .sql.DriverManager;import java.sql.Connection;public class DB { private static final String user = “root”; private static final String password = “123456”; private static final String url = “jdbc:mysql://localhost:3306/signalinfo?useUnicode=true&characterEncoding=UTF-8”; private static Connection cOnn= null; static { init(); } static void init() { try { Class.forName(“com.mysql.jdbc.Driver”); conn = DriverManager.getConnection(url, user, password); } catch (Exception e) { System.out.println( “Database connection error:” + e); } } public static void closeConnection(){ try{ conn.close(); }catch(Exception e){ System.out.println(“An error occurred while closing the database” + e); } } public static Connection getConnection(){ return conn; }} Looking and inserting takes the data separation of China Mobile Signaling as an example. To create a statement and then call stmt.excuteQuery, a ResultSet result set will be returned. Then proceed in detail. For insertion, you must first have a preparedStatement, so that with the sql that can escape?, you can attach the data to be inserted, and then executeUpdate(). package analysis;import java.sql.Connection; import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class transfer { final String MCC = “460”; final String MNC = “00”; // Database connection private static Connection cOnn=…

Java connects to oracle for addition, deletion, modification and query

Java connects to oracle for addition, deletion, modification and query

1. Add class OraclePersionDao to the DAO layer package com.test.dao;import java.sql.*;/** * Created by wdw on 2017/9/16. */public class OraclePersionDao { // Database driver class private String dbDriver = “oracle.jdbc.driver.OracleDriver”; //Connect to database url private String dbURL = “jdbc:oracle:thin:@192.168.31.128:1521:orcl “; // Username to connect to the database private String dbUser = “PHIP”; //Connect to database password private String dbPwd = “PHIP”; // Get the database connection method and return the Connection object private Connection con = null; //Data execution statement private Statement stat = null; private String sql = null; private ResultSet rs = null; //Create database connection public Connection getDBConnect() { try {// Load database driver Class.forName(dbDriver); con = DriverManager.getConnection(dbURL, dbUser, dbPwd); } catch (Exception e) { System.out.println(e); } return con; } //Add public void Add() { con = getDBConnect(); sql = “insert into sys_users(id,code,name )” + “values(‘1′,’lucy’,’w’)”; try { stat = con.createStatement(); stat.executeUpdate(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //Delete public void Delete( ) { con = getDBConnect(); sql = “delete from sys_users ” + “where ID=1”; try { stat = con.createStatement(); stat.executeUpdate(sql); } catch (SQLException e) {// TODO Auto-generated catch block e.printStackTrace(); } } //Modify public void Update() { con…

Use examples to analyze JavaspringbootMongodb addition, deletion, modification and query

This article mainly uses examples to analyze Java springboot Mongodb additions, deletions, modifications and queries. The content is clear and concise. Friends who are interested in this can learn about it. I believe it will be helpful to everyone after reading it. 1. Add dependencies org.springframework.boot spring-boot-starter-data-mongodb 2.1.6.RELEASE Complete pom.xm file 4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.7.RELEASE com.vue demo 0.0.1-SNAPSHOT demo Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-web mysql mysql-connector-java runtime com.alibaba fastjson 1.2.49 com.alibaba druid 1.0.26 org.projectlombok lombok 1.16.20 com.baomidou mybatis-plus-boot-starter 2.2.0 io.springfox springfox-swagger2 2.8.0 io.springfox springfox-swagger-ui 2.8.0 org.springframework.boot spring-boot-starter-data-mongodb 2.1.6.RELEASE org.springframework.boot spring-boot-starter-test test org.junit.vintage junit-vintage-engine org.springframework.boot spring-boot-maven-plugin 2. applicaiton.yml server: port: 8081 mybatis-plus: ​typeAliasesPackage: com.vue.demo.entity ​mapperLocations: classpath:mapper/*.xml spring: datasource: url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezOne=GMT%2B8 username: root password: yang156122 driver-class-name: com.mysql.jdbc.Driver # Use druid data source type: com.alibaba.druid.pool.DruidDataSource redis: #redis stand-alone configuration host: localhost port: 6379 #Select the sub-database of the redis database database: 5 #redis connection pool configuration jedis: pool: max-idle: 10 min-idle: 5 max-active: 100 max-wait: 3000 timeout: 6005 data: mongodb: uri: mongodb://localhost:27017/userArticle 3. Mongodb addition, deletion, modification and query package com.vue.demo.service.serviceimpl; import com.alibaba.fastjson.JSONObject; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; import com.vue.demo.entity.UserArticle; import com.vue.demo.service.UserArticleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Service; import java.util.List; /** * @author yangwj *…

Java operations on mysql database (connection, addition, deletion, modification and query)

java operation on mysql database(connection,add, delete, modify) environment:myeclipse 2014 + tomcat + mysql ( Navicat for mysql) 1. Implement query: package com.mysql;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement; public class DBChaxun {private static final String url &#61 ; “jdbc:mysql://localhost:3306/web”;private static final String user = “root”;private static final String password = “root”;public static void main(String[] args ) throws ClassNotFoundException, SQLException {//1. Load the driver (mysql) Class.forName(“com.mysql.jdbc.Driver”); //2. Get the database connection Connection conn = DriverManager.getConnection(url , user, password); //3. Operate the database through database connection , to implement addition, deletion, modification and query Statement stmt = conn.createStatement(); //Create statement object ResultSet rs = stmt.executeQuery (“select name, age from info”); //(1) Implement the query function , and return the resultset object //4. Get the data in the resultset object while(rs.next()){System.out. println(rs.getString(“name”)+rs.getInt(“age”));}}} 2.Implementdeletion: packagecom.mysql;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;publicclassDBDelete{privatestaticfinalStringurl=”jdbc:mysql://localhost:3306/web”;privatestaticfinalStringuser=”root”;privatestaticfinalStringpassword=”root”;publicstaticvoidmain(String[]args)throwsClassNotFoundException,SQLException{//1.Loadthedriver(mysql)Class.forName(“com.mysql.jdbc.Driver”);//2.GetthedatabaseconnectionConnectionconn=DriverManager.getConnection(url,user,password);//3.Operatethedatabasethroughdatabaseconnection,toimplementaddition,deletion,modificationandqueryStatementstmt=conn.createStatement();//CreatestatementobjectStringsql=”deletefrominfowherename='lry'”;//stmt.execute(sql);//Directlyinsertdataintothedatabasetableintrows=stmt.executeUpdate(sql);System.out.println(“Thenumberofrowsaffectedis:”+rows);}} 3. Implement added (insert): package com.mysql;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException; import java.sql.Statement;public class DBInsert {private static final String url = “jdbc:mysql://localhost:3306/web”;private static final String user = “root”;private static final String password = “root”; public static void main(String[] args) throws ClassNotFoundException, SQLException {//1. Load driver (mysql) Class.forName(“com.mysql.jdbc.Driver”); //2. Get the connection to the database Connection conn = DriverManager.getConnection(url, user, password); //3. Operate the database through the database connection , to implement…

JavaScript addition, deletion, modification and query

push(x) splice elements at the end pop() delete the last element unshift(x) Splice elements at the beginning shift()delete the first element concat(x)Add one array to the end of another array& #xff0c;There must be a variable to accept this value

About java:Spring-Data-jpa learning addition, deletion, modification and query

package com.qijian.domain;import lombok.Data;import javax.persistence.*;/** TODO customer entity class Configure mapping relationship 1. Mapping relationship between entity classes and tables 2. Mapping relationship between attributes in entity classes and fields in tables 1, @Entity: declare entity class @Table: Configure the mapping relationship between entity classes and tables name: The name of the configuration database table *2, * @author qijian. @date 2021/7/25 11:17 */ @Data@Entity@Table(name = “cst_customer”)public class Customer { /** *Customer primary key * @Id: The statement is the configuration of the primary key * @GeneratedValue configures the primary key generation strategy * strategy = GenerationType.IDENTITY:increment * public enum GenerationType{ * TABLE, * SEQUENCE, * IDENTITY, *AUTO * } * The four standard usages provided by JPA are TABLE, SEQUENCE, IDENTITY, and AUTO. * a, TABLE: [Skrill download](https://www.gendan5.com/wallet/Skrill.html) applies a specific database table to retain the primary key. * b, SEQUENCE: Generate the primary key based on the sequence of the underlying database, provided that the database supports the sequence. * c, IDENTITY: The primary key is automatically generated by the database (mainly active growth type) mysql database * d, AUTO: The primary key is controlled by the program * @Column: Mapping relationship between configuration attributes and fields * name: The…

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索