Java鏈接MySql插入數據的代碼java
package com.chendan.maven; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class MavenTest { public static void main(String[] args) throws Exception { String driver = "com.mysql.jdbc.Driver"; // 獲取mysql數據庫的驅動類 String url = "jdbc:mysql://10.0.0.30:3306/test?&useSSL=false"; // 鏈接數據庫(test是數據庫名) String user = "chendan";// 鏈接mysql的用戶名 String password = "123456";// 鏈接mysql的密碼 String insertsql = "insert into t1 values(?,?)"; String querysql = "select * from t1"; Class.forName(driver); Connection conn = DriverManager.getConnection(url, user, password); conn.setAutoCommit(false); PreparedStatement statement = conn.prepareStatement(insertsql); statement.setInt(1, 1); statement.setString(2, "Tom"); statement.executeUpdate(); conn.commit(); ResultSet rst = statement.executeQuery(querysql); while (rst.next()) { System.out.println(rst.getInt(1) + "\t" + rst.getString(2)); } } }