1. 程式人生 > 其它 >Java 連線資料庫 簡單方法

Java 連線資料庫 簡單方法

1、註冊驅動(第一種方法)

    Class.forName(com.mysql.jdbc.Driver");

2、獲得連線DriverManager.getConnection(url,username,password),

    String url = "jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8";
    String username = "root";
    String password = "root";
    Connection conn = DriverManager.getConnection(url,username,password);

3、獲得語句執行平臺connection介面中的creatstatement()方法獲取statement物件

    Statement stat = conn.createStatement();

4、執行sql語句

   Statement常用方法:
    int executeUpdate(String sql); --執行insert update delete語句.
    ResultSet executeQuery(String sql); --執行select語句.

    String sql = "select * from student";
    ResultSet rs = stat.executeQuery(sql);

5、處理結果

  ResultSet介面
    next():判斷是否還有結果
    getXXX():獲取欄位
    rs.getInt(欄位名):獲取int型別的欄位
    rs.getString(欄位名):獲取String型別的欄位
      while(rs.next()) {
      System.out.println("id:"+rs.getInt("id")+",username:"+rs.getString("username"));
      }

6、釋放資源

stat.close();
conn.close();

第二種方法

package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;


public class JdbcDemo3 {

public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.註冊驅動.
Class.forName("com.mysql.jdbc.Driver");

//2.獲得連線. DriverManager.getConnection(url,username,password),
String url = "jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "root";

Connection conn = DriverManager.getConnection(url,username,password);

//3.獲得語句執行平臺 PreparedStatement是Statement的子類物件,有prepareStatement()方法來獲取執行平臺

Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
String psd = sc.nextLine();

//用?代表佔位符
String sql = "select * from student where username = ? and password = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1,name);//數字代表佔位符的索引號從1號開始
ps.setObject(2,psd);

ResultSet rs = ps.executeQuery();//這裡executeQuery()括號內不用再放入sql語句了

// 5.處理結果
while(rs.next()) {
System.out.println("id:"+rs.getInt("id")+",username:"+rs.getString("username"));
}

//6、釋放資源
ps.close();
conn.close();
}

}