JDBC
什么是JDBC
JDBC(Java DataBase Connectivity)是Java和数据库之间的一个桥梁,是一个规范而不是一个实现,能够执行SQL语句。它由一组用Java语言编写的类和接口组成。各种不同类型的数据库都有相应的实现
IDEA连接数据库
1.添加maven依赖
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
2.实现MySQL的连接
3.java代码实现
package com.wang;
import java.sql.*;
public class test {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true";
String username="root";
String password="wjs790929";
//加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//连接数据库
Connection connection = DriverManager.getConnection(url, username, password);
//向数据库发送SQL的对象Statement:增删改查
Statement statement = connection.createStatement();
//编写SQL
String sql="select * from user";
//执行sql,返回一个结果集
ResultSet resultSet = statement.executeQuery(sql);
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("email+"+resultSet.getObject("email"));
}
//关闭连接释放资源
resultSet.close();
statement.close();
connection.close();
}
}
4.增删改返回的是int型,用executeupdate
5.采用预编译经行sql操作更加完善更加安全
package com.wang;
import java.sql.*;
public class test02 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true";
String username="root";
String password="wjs790929";
//加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//连接数据库
Connection connection = DriverManager.getConnection(url, username, password);
//编写sql
String sql="insert into jdbc.user(id, NAME, PASSWORD, email) VALUES (?,?,?,?)";
//预编译
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,4);
preparedStatement.setString(2,"jinnice");
preparedStatement.setString(3,"113456");
preparedStatement.setString(4,"[email protected]");
//执行SQL
int i = preparedStatement.executeUpdate();
if(i>=1)
{
System.out.println("成功");
}
//关闭连接释放资源
preparedStatement.close();
connection.close();
}
}