JAVA操作MySQL數據庫


JAVA操作MySQL數據庫,涉及創建連接,創建表,插入數據,更新數據,查詢數據。

總體步驟:

1) 獲取驅動(可以省略)
2) 獲取連接
  Connection 接口,代表一個連接對象 ,具體的實現類由數據庫的廠商實現
  使用 DriverManager類的靜態方法,getConnection可以獲取數據庫的連接
3) 獲取Statement對象
  通過Connection 的 createStatement方法 獲取sql語句執行對象
4) 處理結果集(只在查詢時處理)
5) 釋放資源
package jdbc;
import java.sql.*;

public class Test01 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
     //使用驅動; Class.forName(
"com.mysql.jdbc.Driver");
     // 創建連接,涉及數據庫IP,端口,數據庫名,字符集,賬號及密碼 String url
= "jdbc:mysql://127.0.0.1:3307/testdb?characterEncoding=UTF-8"; Connection conn = DriverManager.getConnection(url,"root","Root#123456"); //System.out.println(conn); // 獲取語句執行平台對象 Statement Statement smt = conn.createStatement(); // 創建表 executeUpdate方法 String sql1 = "create table if not exists test14(id int primary key auto_increment ,name varchar(20),age int);"; smt.executeUpdate(sql1); // 插入數據 String sql_i = "insert into test14 values(1,'劉備',45),(2,'關羽',40),(3,'張飛',37),(4,'趙雲',30),(5,'諸葛亮',27);"; smt.executeUpdate(sql_i); // 更新數據 String sql_u= "update test14 set age = 36 where name='張飛';"; smt.executeUpdate(sql_u); // 查詢結果 String sql_q = "select * from test14;"; ResultSet res = smt.executeQuery(sql_q); while(res.next()){ int id = res.getInt(1); String name= res.getString("name"); int age = res.getInt("age"); System.out.println("id:"+ id + " name:" + name +" age:"+age); } // 關閉流 (先開后關) res.close(); smt.close(); conn.close(); } }

 結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM