Java串連MySQL,javamysql
1 下載安裝Connector/J,:http://www.mysql.com/products/connector/。Connector/J是專門針對MySQL而開發的JDBC驅動程式套件。
2 將安裝目錄下的mysql-connector-java-5.1.36-bin.jar
添加到環境變數的classpath,或者添加到項目的Java Build Path。
3 JDBC基本編程的步驟:
- 載入驅動
其使用的方法有Class.forName()
或者
Class.forName().newInstance()
或者
new DriverName()
- 串連資料庫
DriverManager.getConnection()
- 執行SQL語句
Connection.CreateStatement()
Statement.executeQuery()
Statement.executeUpdate()
- 取得結果集
while(rs.next())
- 顯示資料
將資料庫中的各種類型轉化為java中的類型(getXXX
)方法
- 關閉
close the resultset
close the statement
close the connection
執行個體:
package ms;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;import java.sql.ResultSet;public class TestMySQL { public static void main(String[] args){ ResultSet rs = null; Statement stmt = null; Connection conn = null; try{ Class.forName("com.mysql.jdbc.Driver"); //建立該字串標識的類的執行個體 String url = "jdbc:mysql://localhost:3306/test"; //標識一個被註冊的驅動程式 String user = "root"; String pwd = ""; conn = DriverManager.getConnection(url, user, pwd); stmt = conn.createStatement(); String query = "select * from person where age > 18"; rs = stmt.executeQuery(query); while (rs.next()){ String id = rs.getString("id"); String name = rs.getString(2); int age = rs.getInt("age"); System.out.println(id + "\t" + name + "\t" + age); } } catch (ClassNotFoundException e){ e.printStackTrace(); } catch (SQLException e){ e.printStackTrace(); } finally { try{ if (rs != null){ rs.close(); } if (stmt != null){ stmt.close(); } if (conn != null){ conn.close(); } } catch (SQLException e){ e.printStackTrace(); } } }}
PreparedStatement的預先處理語句:
String sql = "insert into person values(?,?,?)";PreparedStatement pstmt = conn.prepareStatement(sql);pstmt.setString(1, "005");pstmt.setString(2, "Zhao");pstmt.setInt(3, 18);pstmt.executeUpdate();
statement語句的批處理:
Statement stmt = conn.createStatement();stmt.addBatch("insert into person values('006', 'Zeng', 26)");stmt.addBatch("insert into person values('007', 'Liu', 24)");stmt.addBatch("insert into person values('008', 'Zeng', 17)");stmt.executeBatch();
PreparedStatement語句的批處理
String sql = "insert into person values(?,?,?)";PreparedStatement pstmt = conn.prepareStatement(sql);pstmt.setString(1, "006");pstmt.setString(2, "Zeng");pstmt.setInt(3, 26);pstmt.setString(1, "007");pstmt.setString(2, "Liu");pstmt.setInt(3, 24);pstmt.setString(1, "008");pstmt.setString(2, "Zeng");pstmt.setInt(3, 17);pstmt.executeUpdate();
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。