JDBC介绍
JDBC是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,JDBC对Java程序员而言是API,对与实现数据库连接服务的提供商而言是接口模型。
添加依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
普通查找(未关连接)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Test {
public static final String URL = "jdbc:mysql://localhost:3306/test";
public static final String USER = "root";
public static final String PASSWORD = "123456";
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
Statement stmt = conn.createStatement();
// 查找数据库
ResultSet rs = stmt.executeQuery("SELECT * FROM user");
while (rs.next()) {
System.out.println("姓名: " + rs.getString("name")+",年龄:"+rs.getInt("age"));
}
}
}
普通删除(未关连接)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Test {
public static final String URL = "jdbc:mysql://localhost:3306/test";
public static final String USER = "root";
public static final String PASSWORD = "123456";
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
Statement stmt = conn.createStatement();
// 增,删,改方法,返回影响的行数
int rs = stmt.executeUpdate("DELETE FROM user WHERE name='fei'");
if (rs > 0) {
System.out.println("更新成功!");
} else {
System.out.println("更新失败!");
}
}
}
预编译查找
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class Test {
public static final String URL = "jdbc:mysql://localhost:3306/test";
public static final String USER = "root";
public static final String PASSWORD = "123456";
public static void main(String[] args) {
Connection conn = null;
PreparedStatement prestate = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, USER, PASSWORD);
// 预编译执行对象
prestate = conn.prepareStatement("SELECT * FROM user WHERE name=? AND age=?");
prestate.setString(1, "fei");
prestate.setInt(2, 22);
rs = prestate.executeQuery();
while (rs.next()) {
System.out.println("姓名: " + rs.getString("name") + ",年龄:" + rs.getInt("age"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭连接
close(conn, prestate, rs);
}
}
private static void close(Connection con, Statement sta, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (sta != null) {
sta.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (con != null) {
con.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}