天天看點

用Java操作資料庫

java-mysql

用Java操作資料庫
  • 在有可能讓程式崩潰出錯的地方 光标+Ctrl+1 自動try/catch或throw
  • 用alt+/自動填充代碼塊
  1. 用 ArrayList< > 儲存查詢的傳回結果
    public static ArrayList<Result> getAllResult() { 
    	ArrayList<Result> chengJi = new ArrayList<>();
        //pass
    }
               
  2. 加載驅動,com.mysql.cj.jdbc.Driver就是别人寫好的jar包
  3. 找到資料庫,url:資料庫位址 user資料庫賬号 password :資料庫密碼。url資料庫位址為 jdbc:mysql://127.0.0.1:3306/自己的資料庫名字?連接配接配置不用動。Connection對象根據資料庫位址、賬号、密碼就可以連接配接到資料庫。

    DriverManager驅動管理類得到一個連接配接對象Connection。

  4. sql語句,使用 PreparedStatement 執行sql語句

    根據連接配接對象connection擷取一個執行對象statement

  1. 所有的查詢select都使用 executeQuery() 函數,所有的查詢結果都儲存到 resultSet 結果集。
  1. 從結果集中擷取資料,用 next() 判斷結果集中是否有資料(行)
while(resultSet.next()){
			//從結果集中擷取每一列
			String studentNo = resultSet.getString("studentNo");
			String name = resultSet.getString("studentName");
			int gradeid = resultSet.getInt("gradeid");
			System.out.println(studentNo + "," + name + "," + gradeid);
		}
           
  1. 使用main方法
public static void main(String[] args) throws SQLException {
		//使用查詢全部學生資訊的函數
		getAllStudent();
	}
           
//完整代碼
package cn.ustb.day2;

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

//操作student表
//增删改查
public class StudentDao {

	//查詢全部學生資訊
	public static void getAllStudent() throws SQLException{
		//1、加載驅動
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//2、找到資料庫 url:資料庫位址   user資料庫賬号 password :資料庫密碼
		  //jdbc:mysql://127.0.0.1:3306/自己的資料庫名字?連接配接配置不用動
		  //Connection對象  根據資料庫位址、賬号、密碼就可以連接配接到資料庫
		 Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/myschool?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false&rewriteBatchedStatements=true", "root", "root");
	    //3、sql語句
		 String sql = "select * from student";
		//執行sql語句 : PreparedStatement使用PreparedStatement執行sql語句
		PreparedStatement statement = connection.prepareStatement(sql);
		//使用PreparedStatement的執行方法
		// 所有的查詢select都使用executeQuery()函數
		// 所有的查詢結果都儲存到resultSet
		ResultSet resultSet = statement.executeQuery();
		//從結果集中擷取資料
		//next()判斷結果集中是否有資料(行)
		while(resultSet.next()){
			//從結果集中擷取每一列
			String studentNo = resultSet.getString("studentNo");
			String name = resultSet.getString("studentName");
			int gradeid = resultSet.getInt("gradeid");
			System.out.println(studentNo + "," + name + "," + gradeid);
		}
	}
	
	public static void main(String[] args) throws SQLException {
		//使用查詢全部學生資訊的函數
		getAllStudent();
	}
}