工具:eclipse、MySql、Navicat Premium、
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCDemo2 {
private static final String USERNAME = "root";
private static final String PWD = "lwx";
private static final String dbName = "rzw"; // 數據庫名
private static final String url1 = "jdbc:mysql://localhost:3306/" + dbName;
private static final String url2 = "?user=" + USERNAME + "&password=" + PWD;
private static final String url3 = "&useUnicode=true&characterEncoding=GB2312";
private static final String URL = url1 + url2 + url3; // 形成帶數據庫讀寫編碼的數據庫連接字
// 此方法實現對數據庫的增刪改查 增刪改 一般 是 update(); 查 單獨
public static void update() {// 增刪改
Connection connection = null;
Statement stmt = null;
try {
// a.導入驅動,加載具體的驅動類
Class.forName("com.mysql.jdbc.Driver");// 加載具體的驅動類
// b.與數據庫建立連接
connection = DriverManager.getConnection(URL, USERNAME, PWD);
// c.發送sql,執行(增刪改、查)
stmt = connection.createStatement();
// String sql = "update student set STUNAME='ls' where stuno=1";
// String sql = "delete from student where stuno=1";
// 執行SQL
String sql = "Insert into stu_info values(17,'zs','男',20,70,177)";
int count = stmt.executeUpdate(sql); // 返回值表示 增刪改 幾條數據
// d.處理結果
if (count > 0) {
System.out.println("操作成功!");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null)
stmt.close();// 對象.方法
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
update();
}
}