java_JDBC(4)
注:该篇只是为了小白的我熟悉下JDBC的代码,练习篇
在mysql中建test测试库,并创建一张employees表,加入一些数据如下图:
通过JDBC连接对表中数据进行添加:
package lzj_learn; import java.sql.*; import java.io.*; import java.util.*; public class test2 { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/test"; static final String USER = "root"; static final String PASS = "123456"; public static void main(String[] args) { Connection conn = null; PreparedStatement stmt = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(DB_URL,USER,PASS); String SQL = "INSERT INTO employees(id,age,first,last) VALUES(?,?,?,?)"; stmt = conn.prepareStatement(SQL); conn.setAutoCommit(false); printRows(stmt); stmt.setInt(1, 200); stmt.setInt(2, 18); stmt.setString(3,"xiao"); stmt.setString(4, "zhu"); stmt.addBatch(); stmt.setInt(1, 201); stmt.setInt(2, 19); stmt.setString(3,"xiao"); stmt.setString(4, "cao"); stmt.addBatch(); int[] count = stmt.executeBatch(); conn.commit(); printRows(stmt); stmt.close(); conn.close(); }catch(SQLException se) { se.printStackTrace(); }catch(Exception e) { e.printStackTrace(); }finally { try { if (stmt!=null) stmt.close(); }catch(SQLException se) { } try { if(conn!=null) conn.close(); }catch(SQLException se) { se.printStackTrace(); } } } public static void printRows(Statement stmt) throws SQLException{ String sql = "SELECT * FROM employees"; ResultSet rs = stmt.executeQuery(sql); while(rs.next()) { int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("first"); String last = rs.getString("last"); System.out.print("ID:"+id); System.out.print(",Age:"+ age); System.out.print(",First:"+ first); System.out.println(",Last:"+ last); } System.out.println(); rs.close(); } }
在import时要记得需导入mysql-connector-java-xxxx-jar包;
运行后结果如下: