工具: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();
}
}