用Java执行数据库操作| SQL 创建、插入、更新、删除和选择
本文将帮助您学习如何使用 JDBC(Java数据库连接)API 进行基本的数据库操作。这些基本操作是 SQL 语言中的INSERT、SELECT、UPDATE 和 DELETE语句。虽然目标数据库系统是 Oracle 数据库,但同样的技术也可以应用于其他数据库系统,因为使用的查询语法是标准 SQL,所有关系数据库系统通常都支持。
先决条件:
- JDK
- Oracle 数据库(下载 Oracle 数据库快捷版 11g 第 2 版)
- Oracle 数据库的 JDBC 驱动程序(下载 Oracle 数据库 11g 第 2 版 JDBC 驱动程序)。您需要将ojdbc6.jar添加到项目库中。
在继续更好地理解之前,您需要阅读这篇文章。
在 Oracle 数据库中创建用户并授予所需权限:
- 使用cmd打开oracle。在 cmd 中输入 sqlplus,然后按 Enter。
- 创建受密码保护的用户标识。此用户 ID 称为子用户。
create user identified by ;
- 向子用户授予所需的权限。为简单起见,我们将数据库管理员权限授予子用户。
conn / as sysdba;
grant dba to ;
创建一个带有空白字段的示例表:
CREATE TABLE userid(
id varchar2(30) NOT NULL PRIMARY KEY,
pwd varchar2(30) NOT NULL,
fullname varchar2(50),
email varchar2(50)
);
主要的 JDBC 接口和类
让我们概述一下我们将在本文中使用的 JDBC 的主要接口和类。它们都在Java.sql包下可用:
- Class.forName() :这里我们在运行时将驱动程序的类文件加载到内存中。无需使用新对象或创建对象。
Class.forName("oracle.jdbc.driver.OracleDriver");
- DriverManager:该类用于为特定数据库类型(例如本教程中的 Oracle 数据库)注册驱动程序,并通过其getConnection()方法与服务器建立数据库连接。
- Connection:这个接口表示一个已建立的数据库连接(会话),我们可以从中创建语句来执行查询和检索结果、获取有关数据库的元数据、关闭连接等。
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
- Statement和PreparedStatement :这些接口分别用于执行静态 SQL 查询和参数化 SQL 查询。 Statement是PreparedStatement接口的超接口。他们常用的方法有:
- boolean execute(String sql):执行一般的 SQL 语句。如果查询返回ResultSet则返回true ,如果查询返回更新计数或不返回任何内容,则返回 false。此方法只能与语句一起使用。
- int executeUpdate(String sql):执行 INSERT、UPDATE 或 DELETE 语句并返回一个更新帐户,指示受影响的行数(例如,插入 1 行,或更新 2 行,或影响 0 行)。
Statement stmt = con.createStatement();
String q1 = "insert into userid values
('" +id+ "', '" +pwd+ "', '" +fullname+ "', '" +email+ "')";
int x = stmt.executeUpdate(q1);
- ResultSet executeQuery(String sql):执行 SELECT 语句并返回一个ResultSet对象,该对象包含查询返回的结果。
Statement stmt = con.createStatement();
String q1 = "select * from userid WHERE id = '" + id + "'
AND pwd = '" + pwd + "'";
ResultSet rs = stmt.executeQuery(q1);
- ResultSet:包含 SELECT 查询返回的表数据。使用此对象使用 next() 方法迭代结果集中的行。
- SQLException:这个被检查的异常被声明为上面所有的方法都会抛出,所以我们必须在调用上面的类的方法时显式地捕获这个异常。
连接到数据库
Oracle 数据库服务器在localhost的默认端口1521上进行侦听。以下代码片段通过用户login1和密码pwd1连接到数据库名称userid 。
Java
// Java program to illustrate
// Connecting to the Database
import java.sql.*;
public class connect
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
// Establishing Connection
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
if (con != null)
System.out.println("Connected");
else
System.out.println("Not Connected");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Java
// Java program to illustrate
// inserting to the Database
import java.sql.*;
public class insert1
{
public static void main(String args[])
{
String id = "id1";
String pwd = "pwd1";
String fullname = "geeks for geeks";
String email = "geeks@geeks.org";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();
// Inserting data in database
String q1 = "insert into userid values('" +id+ "', '" +pwd+
"', '" +fullname+ "', '" +email+ "')";
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("Successfully Inserted");
else
System.out.println("Insert Failed");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Java
// Java program to illustrate
// updating the Database
import java.sql.*;
public class update1
{
public static void main(String args[])
{
String id = "id1";
String pwd = "pwd1";
String newPwd = "newpwd";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();
// Updating database
String q1 = "UPDATE userid set pwd = '" + newPwd +
"' WHERE id = '" +id+ "' AND pwd = '" + pwd + "'";
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("Password Successfully Updated");
else
System.out.println("ERROR OCCURED :(");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Java
// Java program to illustrate
// deleting from Database
import java.sql.*;
public class delete
{
public static void main(String args[])
{
String id = "id2";
String pwd = "pwd2";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();
// Deleting from database
String q1 = "DELETE from userid WHERE id = '" + id +
"' AND pwd = '" + pwd + "'";
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("One User Successfully Deleted");
else
System.out.println("ERROR OCCURED :(");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Java
// Java program to illustrate
// selecting from Database
import java.sql.*;
public class select
{
public static void main(String args[])
{
String id = "id1";
String pwd = "pwd1";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();
// SELECT query
String q1 = "select * from userid WHERE id = '" + id +
"' AND pwd = '" + pwd + "'";
ResultSet rs = stmt.executeQuery(q1);
if (rs.next())
{
System.out.println("User-Id : " + rs.getString(1));
System.out.println("Full Name :" + rs.getString(3));
System.out.println("E-mail :" + rs.getString(4));
}
else
{
System.out.println("No such user id is already registered");
}
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output :
Connected
注意:这里 getConnection() 方法中数据库 URL 中的oracle指定了 Oracle 数据库的 SID。对于 Oracle 数据库 11g,它是orcl ,对于 Oracle 数据库 10g,它是xe 。
实现插入语句
Java
// Java program to illustrate
// inserting to the Database
import java.sql.*;
public class insert1
{
public static void main(String args[])
{
String id = "id1";
String pwd = "pwd1";
String fullname = "geeks for geeks";
String email = "geeks@geeks.org";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();
// Inserting data in database
String q1 = "insert into userid values('" +id+ "', '" +pwd+
"', '" +fullname+ "', '" +email+ "')";
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("Successfully Inserted");
else
System.out.println("Insert Failed");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output :
Successfully Registered
执行更新语句
Java
// Java program to illustrate
// updating the Database
import java.sql.*;
public class update1
{
public static void main(String args[])
{
String id = "id1";
String pwd = "pwd1";
String newPwd = "newpwd";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();
// Updating database
String q1 = "UPDATE userid set pwd = '" + newPwd +
"' WHERE id = '" +id+ "' AND pwd = '" + pwd + "'";
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("Password Successfully Updated");
else
System.out.println("ERROR OCCURED :(");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output :
Password Successfully Updated
实现删除语句
Java
// Java program to illustrate
// deleting from Database
import java.sql.*;
public class delete
{
public static void main(String args[])
{
String id = "id2";
String pwd = "pwd2";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();
// Deleting from database
String q1 = "DELETE from userid WHERE id = '" + id +
"' AND pwd = '" + pwd + "'";
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("One User Successfully Deleted");
else
System.out.println("ERROR OCCURED :(");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output :
One User Successfully Deleted
实现 Select 语句
Java
// Java program to illustrate
// selecting from Database
import java.sql.*;
public class select
{
public static void main(String args[])
{
String id = "id1";
String pwd = "pwd1";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();
// SELECT query
String q1 = "select * from userid WHERE id = '" + id +
"' AND pwd = '" + pwd + "'";
ResultSet rs = stmt.executeQuery(q1);
if (rs.next())
{
System.out.println("User-Id : " + rs.getString(1));
System.out.println("Full Name :" + rs.getString(3));
System.out.println("E-mail :" + rs.getString(4));
}
else
{
System.out.println("No such user id is already registered");
}
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output :
User-Id : id1
Full Name : geeks for geeks
E-mail :geeks@geeks.org
注意:这里的列索引是从 1 开始的,第一列将在索引 1 处,第二列在索引 2 处,依此类推。
对于其他数据类型,ResultSet 提供了适当的 getter 方法:
- 获取字符串()
- 获取整数()
- 获取浮动()
- 获取日期()
- 获取时间戳()
- ……