导入jar包
- 下载jar包mysql-connector-java-5.0.8-bin.jar
jar包下载地址(https://download.csdn.net/download/yangsen251024/3680834) - 在工程中新建文件夹lib
- 把jar包放入文件夹lib中
- 右击jar包,选择Add as library
完成jar包导入,开始进行数据库操作
try{
//1.加载驱动
class.forName("com.mysql.jdbc.Driver");
//2.创建连接
conn = DriverManager.getConnection("jdbc:mysql://localhost/nd?user=root&password=root");
/*Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/nd?useSSL=true&characterEncoding=utf-8&user=root&password=root");
第二种连接方式 */
System.out.print("创建连接成功\n");
}catch(Exception e) {
e.printStackTrace();
}
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
//3.写sql
String sql="Select * from tb_user";
// 4.得到statement对象
preparedStatement = conn.prepareStatement(sql);
// 5.执行sql
resultSet = preparedStatement.executeQuery();
PreparedStatement preparedStatement=null;
//3.写sql
String sql="INSERT INTO tb_user (username,password) VALUES ("+"\'"+un+"\'"+","+"\'"+pw+"\'"+")";
// 4.得到statement对象
preparedStatement = conn.prepareStatement(sql);
// 5.执行sql
preparedStatement.executeUpdate();
System.out.print("添加成功");
PreparedStatement preparedStatement=null;
//3.写sql
String sql = "delete from tb_user where id="+"\'"+id+"\'";
// 4.得到statement对象
preparedStatement = conn.prepareStatement(sql);
// 5.执行sql
preparedStatement.executeUpdate();
// 6.处理结果集
System.out.print("删除成功");
PreparedStatement preparedStatement=null;
//3.写sql
String sql = "update tb_user set password ="+"\'"+pw+"\'"+" where id ="+"\'"+id+"\'";
// 4.得到statement对象
preparedStatement = conn.prepareStatement(sql);
// 5.执行sql
preparedStatement.executeUpdate();
// 6.处理结果集
System.out.print("修改成功");
finally {
try{
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
preparedStatement.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
查找功能使用 executeQuery()
其余三个功能使用 executeUpdate()
以上是通过JDBC对Mysql数据库的"增删改查"功能的具体实现