使用eclipse来新增数据
public static void main(String[] args) throws ClassNotFoundException {
// 第一步 首先加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 第二步 然后获取数据库连接
// 连接字符串
String url = "jdbc:mysql://localhost:3306/demo_db_2021?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false";
// 用户名 密码
String userName = "root";
String password = "root";
Connection conn = null;
PreparedStatement ps = null;
try {
conn = DriverManager.getConnection(url, userName, password);
// 第三步 创建Statement
// prepareStatement 中使用?作为变量的占位符
String strSql = "INSERT INTO sys_user(user_name,user_passwork,real_name,sex,age,birthday,phone,address,user_roleid) "
+ "VALUE(?,?,?,?,?,?,?,?,?)";
ps = conn.prepareStatement(strSql);
// 第四步 新增数据参数赋值
Date date = new Date();
ps.setString(1, "liWei");
ps.setString(2, "1267");
ps.setString(3, "李伟");
ps.setByte(4, (byte) 1);
ps.setInt(5, 23);
ps.setDate(6, new java.sql.Date(date.getTime()));
ps.setString(7, "宁要曹县一张床,不要上海一套房");
ps.setString(8, "山东菏泽");
ps.setInt(9, 9);
// 第五步 执行sql
int rows = ps.executeUpdate();// 返回受影响的行数
if (rows == 1) {
System.out.println("新增成功");
} else {
System.out.println("新增失败");
}
} catch (SQLException e) {
// TODO: Auto-generated catch block
e.printStackTrace();
} finally {
if (conn != null) {
// 记住一定要关闭数据库连接
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
运行后如果数据新增成功控制台返回新增成功,否则返回新增失败