1,创建如下的数据
2,在idea中导入MySQL的jar
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
3,加载驱动(jdk8之后可以不加载驱动,驱动被jdk8以内置)------配置信息(url,usernname,password)----------连接数据库----------向数据库发送SQL对象,编写sql语句-------------执行ssql----------------最后释放内存(先开的后释放)
一:查询
public class TestJdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
//useUnicode=true&characterEncoding=utf-8配置中午乱码问题
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "456789";
//1,加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2,连接数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3,向数据库发送SQL对象的Statement:CRUD
Statement statement = connection.createStatement();
//4,编写sql
String sql = "select * from users";
//5,执行查询SQL,返回一个结果集
ResultSet resultSet = statement.executeQuery(sql);
//6,打印结果集
while (resultSet.next()){
System.out.println("id:"+resultSet.getObject("id"));
System.out.println("name:"+resultSet.getObject("name"));
System.out.println("password:"+resultSet.getObject("password"));
System.out.println("birthday:"+resultSet.getObject("birthday"));
}
//7,关闭连接释放资源
resultSet.close();
statement.close();
connection.close();
}
}
二:添加数据
public class TestJdbc2 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
//useUnicode=true&characterEncoding=utf-8配置中午乱码问题
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "456789";
//1,加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2,连接数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3,编写sql
String sql = "insert into users(id,name,password,email,birthday) values (?,?,?,?,?);";
//4,预编译
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,5);//给第一个占位符赋值为1
preparedStatement.setString(2,"吴彦祖");
preparedStatement.setString(3,"1263781");
preparedStatement.setString(4,"wyz@qq.com");
preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));
//5,执行sql
int i = preparedStatement.executeUpdate();
if (i>0){
System.out.println("插入成功!!!");
}
//5,关闭连接释放资源
preparedStatement.close();
connection.close();
}
}
4.,注意:配置信息如果不想这样显示在main中,可以写一个.properties文件存放配置信息
# 名为 jdbc.properties 的配置文件,不需要以分号结尾。
url=jdbc:mysql://localhost:3306/jdbc
username=root
password=456789
driver=com.mysql.jdbc.Driver
5,然后再main函数中读取.properties文件取代url,username以及password即可