標籤:
/************************************************************************* > File Name: Mysql.java > Author: Baiyan > 題意: > Created Time: 2016年06月04日 星期六 01時03分32秒 **********************************************************************/import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import com.mysql.jdbc.Connection;import java.sql.Statement;public class Mysql{ public static void main(String[] args) throws Exception { Connection conn = null; String url = "jdbc:mysql://localhost:3306/sample?"+"user=root&password=www1964878036&useUnicode=true&characterEncoding=UTF-8"; //先載入Mysql驅動類; try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("驅動載入成功!"); conn = (Connection) DriverManager.getConnection(url); //connection 代表一個資料庫的連結; // //要執行sql語句必須獲得java.sql.Statement執行個體; Statement stmt = conn.createStatement(); //Statement 執行個體有以下三種: //執行靜態sql語句,通過Statement 執行個體實現; //執行動態sql語句,通過PreparedStatement執行個體實現; //執行資料庫預存程序,通常通過CallableStatement執行個體實現; //上面是其中一種,下面給出另外兩種; // //PreparedStatement pstmt = conn.preparesStatement(sql); //CallableStatement cstmt = con.prepareCall("{CALL demoSp(?,?)}"); // //然後是執行sql語句; //有三種執行sql語句的方法 //executeQuery、executeUpdate、execute // //說一下三者的用法 String Sql="create table student(id char(20), name char(20),primary key(id))"; int result = stmt.executeUpdate(Sql); //返回受影響的行數; //返回-1就表示沒有成功; ResultSet rs = null; if(result != -1) { Sql = "insert into student(id,name) values(‘1234‘,‘biayan‘)"; result = stmt.executeUpdate(Sql); Sql="select * from student"; rs = stmt.executeQuery(Sql); //這句返回結果集合; while(rs.next()) { System.out.println(rs.getString(1)+"\t"+rs.getString(2)); } } //可以看出,Query用於處理查詢類的; //Update用於Insert、Update、delete、Drop; //另一個用於組合的語句; //對於結果集也可以使用getString("name")的方式活取內容; //列是從1開始編號的; // // //然後要關閉串連; if(rs!=null)//關閉記錄集; {try { rs.close(); }catch(SQLException e) { e.printStackTrace(); } } if(stmt !=null)//關閉聲明; { try{ stmt.close(); }catch(SQLException e){ e.printStackTrace(); } } if(conn!=null) { try { conn.close(); }catch(SQLException e) { e.printStackTrace(); } } }catch (ClassNotFoundException e) { System.out.println("找不到驅動程類,載入驅動失敗"); e.printStackTrace(); } //載入成功後,會將Mysql的Driver類的執行個體註冊到DriverManger類中; }}
java連結資料庫--Mysql