JDBC beginner (1): connection and operation

JDBC(Java DataBase Connectivity) Java数据库连接 
其实就是利用Java语言/程序连接并访问数据库的一门技术
之前我们可以通过cmd或者SQLyog等工具连接操作数据库
但在企业开发中,更多的是通过程序(Java程序)连接并访问数据库,通过Java程序访问数据库,就需要用到JDBC这门技术。

The first step: First, we prepare the data we need to operate in the mysql database:
create database jt_db charset utf8;
use jt_db;
create table account(
id int primary key auto_increment,
name varchar(50),
money double
);
insert into account values(null,'tom', 1000);
insert into account values(null,'andy', 1000);
insert into account values(null,'tony', 1000);
we create the jt_db database in the database and create the account table And insert data.

2. Step 2: Import the mysql driver package
in
As shown in the figure above, create a Folder in the java project and name it lib. After finding the mysql-connector-java-5.1.32.jar compressed package on the Internet, paste it into the lib.
Insert picture description here
After that, we right-click the mysql-connector-java-5.1.32.jar compressed package, select buildpath->add to build path
as shown in the figure above, and we will find that there is a bottle-shaped logo in our Referenced Libraries.

Step 3: Create the class and implement the jdbc program (six steps):
1. Register the database driver
*2. Get the database connection
*3. Get the transmitter
*4. Send SQL to the server through the transmitter, and return the execution result
*5 .Output results (output each row of records to the console)
*6. Dilute resources
*
Note: My mysql database account and password are both root, and the port is also 3306. The
code is as follows:


	public static void main(String[] args) throws Exception {
    
    
		/**
		 * *1.注册数据库驱动(参数是Driver类的权限定类名)
		 */
		try {
    
    
			Class.forName("com.mysql.jdbc.Driver");//反射Driver类,使其运行,其中的静态代码块注册
		} catch (ClassNotFoundException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/**
		 * 	*2.获取数据连接:(三个参数,连接数据库的url,数据库的用户名,密码)
		 */
		Connection conn=DriverManager.getConnection(
				"jdbc:mysql://localhost:3306/jt_db?characterEncoding=utf-8","root","root");
		/**
		 *  *3.获取传输
		 */
		Statement stat=conn.createStatement();//Statement传输器
		/**
		 * *4.通过传输器发送SQL到服务器,并返回执行结果
		 */
		String sql="select * from account                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             ";
		//将 sql语句传到数据库
		ResultSet rs=stat.executeQuery(sql);//executeQuery用于执行查询类型的SQL语句
		/**
		 * *5.输出结果(将每一行记录输出到控制台上)
		 */
//		rs.next();//让箭头向下挪动一行,返回布尔值
//		rs.getInt("id");
//		rs.getString("name");
//		rs.getDouble("money");
		System.out.println("id\t"+"name\t"+"money\t");
		while(rs.next()) {
    
    
			int id=rs.getInt("id");
			String name=rs.getString("name");
			double money=rs.getDouble("money"); 
			
			System.out.println(id+"\t"+name+"\t"+money+"\t");
		}
		/**
		 * *6.稀释资源
		 */
		rs.close();
		stat.close();
		conn.close();

		//syst  alt+/
		System.out.println("TertJDBC01.main()");
		
		
	
	}

The results are as follows:
Insert picture description here

It is not difficult to find that the format of the first step of registering the driver and the second step of obtaining the database connection in the JDBC connection step is constant (except for the URL, database account and password parameters).
Therefore, for the convenience of future use, we The first and second steps can be encapsulated into a class method, and for future use, we only need to call the method of this class to directly get the connection.
The method is as follows:
as shown in the figure, we create a new package under the current project, and create a new connection-generating class in the package.
Insert picture description here
After that, we can write two methods in the class:
a getConn() method with no parameters and a getConn() method with parameters In the getConn() method
without parameters, we default the url, the account and password have been determined, this is for the convenience of calling the method, in the method with parameters, we are mainly to facilitate when our url, account or password is changed modify. (Just change the parameters)

public class jdbcUtil {
    
    
	//获取连接的方法
	public static Connection getConn(){
    
    
		try {
    
    
			Class.forName("com.mysql.jdbc.Driver");
			//获取连接:
			String url="jdbc:mysql://localhost:3306/jt_db?characterEncoding=utf-8";
			String user="root";
			String pwd="root";
			Connection conn=DriverManager.getConnection(url,user,pwd);
			return conn;
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取数据库连接对象
	 * @param dbName 连接数据库的名字
	 * @param user  连接数据可的用户名
	 * @param pwd 连接的数据库的密码
	 * @return Connection连接对象
	 */
	public static Connection getConn(String dbName,String user,String pwd){
    
    
		try {
    
    
			Class.forName("com.mysql.jdbc.Driver");
			//获取连接:
			String url="jdbc:mysql://localhost:3306/"+dbName+"?characterEncoding=utf-8";
			Connection conn=DriverManager.getConnection(url,user,pwd);
			return conn;
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
		return null;
	}
}

After we encapsulate the connection method, it is convenient to call it.
At the beginning of the fourth step, we only performed a query operation on the database after connecting to the database with java (executeQuery() function, the return value is the data collection in the database), however, we add, delete, and modify the database. Need to use another function (executeUpdate () function, the return value is the number of data rows affected by the operation).

@Test
	public void testInsert() throws Exception {
		//新增:
		Class.forName("com.mysql.jdbc.Driver");
		//获取连接:
		String url="jdbc:mysql://localhost:3306/jt_db?characterEncoding=utf-8";
		String user="root";
		String pwd="root";
		Connection conn=DriverManager.getConnection(url,user,pwd);
		//获取传输器:
		Statement stat=conn.createStatement();
		//执行sql,返回结果
		String sql = "insert into account value(null,'john',3500)";
		int rows=stat.executeUpdate(sql);//返回行数
		//输出结果
		System.out.println("影响行数:"+rows);
		//释放资源
		stat.close();
		conn.close();
		
	}
删除操作:
@Test
	public void testDelete() throws Exception {
    
    
		//删除:
		Connection conn=jdbcUtil.getConn();
		Statement stat=conn.createStatement();
		String sql ="delete from account where id=4";
		int rows=stat.executeUpdate(sql);
		System.out.println("影响行数:"+rows);
		//释放资源
		stat.close();
		conn.close();
	}
更改操作:
@Test
	public void testUpdate() throws Exception {
    
    
		//修改:
		Connection conn=jdbcUtil.getConn();
		Statement stat=conn.createStatement();
		String sql ="update account set money=1500 where name='john'";
		int rows=stat.executeUpdate(sql);
		System.out.println("影响行数:"+rows);
		//释放资源
		stat.close();
		conn.close();
	}
	
查询操作:
@Test
	public void testSelect() throws Exception{
    
    
		Connection conn=jdbcUtil.getConn("jt_db","root", "root");
		Statement stat=conn.createStatement();
		String sql="select * from account";
		ResultSet rs=stat.executeQuery(sql);
		
		System.out.println("id\t"+"name\t"+"money\t");
		while(rs.next()) {
    
    
			int id=rs.getInt("id");
			String name=rs.getString("name");
			double money=rs.getDouble("money"); 
			
			System.out.println(id+"\t"+name+"\t"+money+"\t");
		}
		
		rs.close();
		stat.close();
		conn.close();
	}

Guess you like

Origin blog.csdn.net/qq_45273552/article/details/107069779