JAVA EE NZ2001 --Day39 - java EE study all night, finally somehow related summary database connection, operation and notes

1, a user queries a table, all of the package to the user to show a list which

Description: code shown which is connected to the database I nz2001, the representations of operations user_info table representation
wherein the design table in FIG.
Here Insert Picture Description

package com.qianfeng.ps.am.secend;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class DemoList {
	public static void main(String[] args) {

	String url = "jdbc:mysql://127.0.0.1:3306/nz2001";
	String user = "root";
	String password ="123456";
	
	Connection con = null;
	PreparedStatement ps = null;
	ResultSet rs = null; //结果集
	
	
	try {
		Class.forName("com.mysql.jdbc.Driver"); //加载驱动use
		
		con = DriverManager.getConnection(url,user,password); //获取连接
		
		//从现在开始,养成良好的习惯; 不用*
		String sql = "select uid,uname,upass,uage from user_info";
		
		//获取预处理对象
		ps = con.prepareStatement(sql); //给了sql
		
		//执行查询 得到结果集
		rs = ps.executeQuery();
		
		//新建一个集合 ; 将结果集里面的数据, 封装到这个集合里面去
		List<UserInfo> list = new ArrayList<UserInfo>();
		UserInfo ui;
		
		//一次循环,是一行(条)数据
		while(rs.next()) { //遍历查询结果;每循环一次,就代表有一行数据
			
			//实例化一个UserInfo的对象;
			ui = new UserInfo(); // 每次都要实例化对象
			
			//要将这个数据保存到  ui对象里面去
			ui.setUid(rs.getInt("uid"));
			ui.setUname(rs.getString("uname"));
			ui.setUpass(rs.getString("upass"));
			ui.setUage(rs.getInt("uage"));
			
			//把这个ui对象,添加到集合里面去
			list.add(ui); //存进去的不是ui这个引用名称,存的是引用  x001x01   x002123   x1231231
		}
		
		//关闭连接
		rs.close();
		ps.close();
		con.close();
		
		for(UserInfo aa : list) {
			System.out.println(aa);
		}
		
		
	}catch (Exception e) {
		e.printStackTrace();
	}
	}

}

2, using the configuration file encapsulated DBtuil

package com.qianfeng.ps.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtils {

	// 不变
	static final String URL = "jdbc:mysql://127.0.0.1:3306/nz2001?rewriteBatchedStatements=true";
	static final String USER = "root";
	static final String PASS_WORD = "123456";

	// 1: 加载驱动,在我们整个项目里面,只需要跑一次;

	static {
		// 加载驱动;
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	// 提供静态方法获取数据库的连接;
	/**
	 * 返回一个数据库的连接
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		try {
			return DriverManager.getConnection(URL, USER, PASS_WORD);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 提供静态方法,关闭我们的结果集; 关闭我们的 ps对象; 关闭我们的连接对象;
	public static void close(Connection con, PreparedStatement ps, ResultSet rs) {

		closeResultSet(rs); // 关闭结果集

		closePreparedStatement(ps); //关闭操作数据库的对象
		
		closeConnection(con);//关闭连接
	}

	private static void closeResultSet(ResultSet rs) {

		if (rs != null) {

			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}

	}

	private static void closePreparedStatement(PreparedStatement ps) {
		if (ps != null) {

			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}
	}
	
	private static void closeConnection(Connection con) {
		if (con != null) {

			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}
	}

}

3, the step of operation of the database and the main java interface class

**


step


  1. Import JDBC driver package: the package needs to download the jar containing the desired JDBC database programming.

  2. Register JDBC Driver: Requires you to initialize the driver so that you can open a communication channel with the database.

  3. Create a connection: the need to use D riv er M anage rg et C onnec tio n ()
    to create a Connection object method, the object represents a physical connection to the database.

  4. Execute the query: the need to build an object Statement SQL statements submitted to the database and type of use.

  5. Data from the result to extracting: the need to use the corresponding R es ult S et .get XXX () methods to retrieve values ​​from the result.

  6. The release of resources: the need to explicitly close all database resources, without relying on the JVM's garbage collection.

**

The detailed operation of step

**
(1) Import jar package, create a lib directory under the project, the jdbc mysql packages into this directory, and add to the build path of (different idea).
Here Insert Picture Description
FIG database driver
Here Insert Picture Description
Here Insert Picture Description
in FIG.
Here Insert Picture Description

(2) registration drive

The first method (recommended wording): Class.forName ()
The most common method is to use a registered driver of Java Class.forName () method, the class file for the driver dynamically loaded into memory and automatically register

try {  
 Class.forName("com.mysql.jdbc.Driver"); 
 } 
 catch(ClassNotFoundException ex) {
    System.out.println("Error: unable to load driver class!");   
    System.exit(1); 
    }


 

The second way: use static DriverManager.registerDriver () method.

try { 
  Driver myDriver = new com.mysql.jdbc.Driver();
     DriverManager.registerDriver( myDriver );
      } 
      catch(ClassNotFoundException ex) { 
        System.out.println("Error: unable to load driver class!"); 
          System.exit(1); 
          }

(3) obtaining a connection
3.1 URL database configuration
after loading the driver can use the DriverManager.getConnection () method to establish a connection. For ease of reference, let me list three overloaded DriverManager.getConnection () method

  • getConnection(String url
    **
    getConnection(String url,Properties prop)
    **
  • getConnection(String url,String user,String password)

Create a database connection object

String URL = "jdbc:mysql://localhost:3306/emp"; 
String USER = "root"; 
String PASS = "root" Connection conn = DriverManager.getConnection(URL, USER, PASS);

The main interface

Statement Universal access to the database. Useful when using static SQL statements at run time. Statement interfaces can not accept parameters.
PreparedStatement (recommended ) ** use when you plan to use multiple SQL statements. PreparedStatement interface accepts input parameters at runtime.
**
Published 32 original articles · won praise 9 · views 3155

Guess you like

Origin blog.csdn.net/weixin_43501566/article/details/105131568