jdbc的用法
来源:互联网 发布:知乎的live可以下载吗 编辑:程序博客网 时间:2024/06/05 20:58
一,JDBC基本操作
为了简单起见,与数据库相关的操作、命令、参数都被硬编码了。有兴趣的读者可以对这些进行探索,降低数据与操作的耦合性。
先看具体代码并实践,本文第五部分对用到的API稍作了研究。
下面的所有方法和数据成员都在public class JDBCOperation内部。
(1)定义记录的类(可选)
这样做主要是为了便于操作和接口定义,是非必须的。
复制代码
static class Student {
private String Id;
private String Name;
private String Sex;
private String Age;
Student(String Name, String Sex, String Age) {
this.Id = null; //default
this.Name = Name;
this.Sex = Sex;
this.Age = Age;
}
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getSex() {
return Sex;
}
public void setSex(String Sex) {
this.Sex = Sex;
}
public String getAge() {
return Age;
}
public void setage(String Age) {
this.Age = Age;
}
}
复制代码
(2)连接的获取
在操作前必须先获取与数据库的连接。
driver、url的格式同样可以参考各种数据库对应的jar包、驱动类名和URL格式。
复制代码
private static Connection getConn() {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/samp_db";
String username = "root";
String password = "";
Connection conn = null;
try {
Class.forName(driver); //classLoader,加载对应驱动
conn = (Connection) DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
复制代码
(3)insert
复制代码
private static int insert(Student student) {
Connection conn = getConn();
int i = 0;
String sql = "insert into students (Name,Sex,Age) values(?,?,?)";
PreparedStatement pstmt;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
pstmt.setString(1, student.getName());
pstmt.setString(2, student.getSex());
pstmt.setString(3, student.getAge());
i = pstmt.executeUpdate();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return i;
}
复制代码
(4)update
复制代码
private static int update(Student student) {
Connection conn = getConn();
int i = 0;
String sql = "update students set Age='" + student.getAge() + "' where Name='" + student.getName() + "'";
PreparedStatement pstmt;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
i = pstmt.executeUpdate();
System.out.println("resutl: " + i);
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return i;
}
复制代码
(5)select
以select * from XXX为例。
复制代码
private static Integer getAll() {
Connection conn = getConn();
String sql = "select * from students";
PreparedStatement pstmt;
try {
pstmt = (PreparedStatement)conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
int col = rs.getMetaData().getColumnCount();
System.out.println("============================");
while (rs.next()) {
for (int i = 1; i <= col; i++) {
System.out.print(rs.getString(i) + "\t");
if ((i == 2) && (rs.getString(i).length() < 8)) {
System.out.print("\t");
}
}
System.out.println("");
}
System.out.println("============================");
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
复制代码
(6)delete
复制代码
private static int delete(String name) {
Connection conn = getConn();
int i = 0;
String sql = "delete from students where Name='" + name + "'";
PreparedStatement pstmt;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
i = pstmt.executeUpdate();
System.out.println("resutl: " + i);
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return i;
}
复制代码
二、测试
在测试前,需要在系统中打开对应数据库的服务。MySQL在Windows下的启动命令为
net start mysql
测试代码
复制代码
public static void main(String args[]) {
JDBCOperation.getAll();
JDBCOperation.insert(new Student("Achilles", "Male", "14"));
JDBCOperation.getAll();
JDBCOperation.update(new Student("Bean", "", "7"));
JDBCOperation.delete("Achilles");
JDBCOperation.getAll();
}
复制代码
Eclipse中的输出
复制代码
============================
1 Ender male 8
2 Bean male 6
3 Petra fema 9
4 Peter male 9
5 _Graff male 40
6 GOD fema 255
============================
============================
1 Ender male 8
2 Bean male 6
3 Petra fema 9
4 Peter male 9
5 _Graff male 40
6 GOD fema 255
7 Achilles Male 14
============================
resutl: 1
resutl: 1
============================
1 Ender male 8
2 Bean male 7
3 Petra fema 9
4 Peter male 9
5 _Graff male 40
6 GOD fema 255
============================
复制代码
三、代码分析
在上述对数据库进行增删改查的过程中,可以发现其共性部分,即通用的流程:
(1)创建Connection对象、SQL查询命令字符串;
(2)对Connection对象传入SQL查询命令,获得PreparedStatement对象;
(3)对PreparedStatement对象执行executeUpdate()或executeQurey()获得结果;
(4)先后关闭PreparedStatement对象和Connection对象。
可见,使用JDBC时,最常打交道的是Connection、PreparedStatement这两个类,以及select中的ResultSet类。查阅Java API手册可以了解其具体的意义和方法。
下面引用的Java API的资料出自http://download.oracle.com/technetwork/java/javase/6/docs/zh/api/index.html。
Connection
java.sql
接口 Connection
所有超级接口:
Wrapper
public interface Connectionextends Wrapper
与特定数据库的连接(会话)。在连接上下文中执行 SQL 语句并返回结果。
Connection 对象的数据库能够提供描述其表、所支持的 SQL 语法、存储过程、此连接功能等等的信息。此信息是使用 getMetaData 方法获得的。
PreparedStatemnt
java.sql
接口 PreparedStatement
所有超级接口:
Statement, Wrapper
所有已知子接口:
CallableStatement
public interface PreparedStatementextends Statement
表示预编译的 SQL 语句的对象。
SQL 语句被预编译并存储在 PreparedStatement 对象中。然后可以使用此对象多次高效地执行该语句。
常用方法
boolean execute()
在此 PreparedStatement 对象中执行 SQL 语句,该语句可以是任何种类的 SQL 语句。
ResultSet executeQuery()
在此 PreparedStatement 对象中执行 SQL 查询,并返回该查询生成的 ResultSet 对象。
int executeUpdate()
在此 PreparedStatement 对象中执行 SQL 语句,该语句必须是一个 SQL 数据操作语言(Data Manipulation Language,DML)语句,比如 INSERT、UPDATE 或 DELETE 语句;或者是无返回内容的 SQL 语句,比如 DDL 语句。
ResultSet
java.sql
接口 ResultSet
所有超级接口:
Wrapper
所有已知子接口:
CachedRowSet, FilteredRowSet, JdbcRowSet, JoinRowSet, RowSet, SyncResolver, WebRowSet
public interface ResultSetextends Wrapper
表示数据库结果集的数据表,通常通过执行查询数据库的语句生成。
为了简单起见,与数据库相关的操作、命令、参数都被硬编码了。有兴趣的读者可以对这些进行探索,降低数据与操作的耦合性。
先看具体代码并实践,本文第五部分对用到的API稍作了研究。
下面的所有方法和数据成员都在public class JDBCOperation内部。
(1)定义记录的类(可选)
这样做主要是为了便于操作和接口定义,是非必须的。
复制代码
static class Student {
private String Id;
private String Name;
private String Sex;
private String Age;
Student(String Name, String Sex, String Age) {
this.Id = null; //default
this.Name = Name;
this.Sex = Sex;
this.Age = Age;
}
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getSex() {
return Sex;
}
public void setSex(String Sex) {
this.Sex = Sex;
}
public String getAge() {
return Age;
}
public void setage(String Age) {
this.Age = Age;
}
}
复制代码
(2)连接的获取
在操作前必须先获取与数据库的连接。
driver、url的格式同样可以参考各种数据库对应的jar包、驱动类名和URL格式。
复制代码
private static Connection getConn() {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/samp_db";
String username = "root";
String password = "";
Connection conn = null;
try {
Class.forName(driver); //classLoader,加载对应驱动
conn = (Connection) DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
复制代码
(3)insert
复制代码
private static int insert(Student student) {
Connection conn = getConn();
int i = 0;
String sql = "insert into students (Name,Sex,Age) values(?,?,?)";
PreparedStatement pstmt;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
pstmt.setString(1, student.getName());
pstmt.setString(2, student.getSex());
pstmt.setString(3, student.getAge());
i = pstmt.executeUpdate();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return i;
}
复制代码
(4)update
复制代码
private static int update(Student student) {
Connection conn = getConn();
int i = 0;
String sql = "update students set Age='" + student.getAge() + "' where Name='" + student.getName() + "'";
PreparedStatement pstmt;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
i = pstmt.executeUpdate();
System.out.println("resutl: " + i);
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return i;
}
复制代码
(5)select
以select * from XXX为例。
复制代码
private static Integer getAll() {
Connection conn = getConn();
String sql = "select * from students";
PreparedStatement pstmt;
try {
pstmt = (PreparedStatement)conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
int col = rs.getMetaData().getColumnCount();
System.out.println("============================");
while (rs.next()) {
for (int i = 1; i <= col; i++) {
System.out.print(rs.getString(i) + "\t");
if ((i == 2) && (rs.getString(i).length() < 8)) {
System.out.print("\t");
}
}
System.out.println("");
}
System.out.println("============================");
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
复制代码
(6)delete
复制代码
private static int delete(String name) {
Connection conn = getConn();
int i = 0;
String sql = "delete from students where Name='" + name + "'";
PreparedStatement pstmt;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
i = pstmt.executeUpdate();
System.out.println("resutl: " + i);
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return i;
}
复制代码
二、测试
在测试前,需要在系统中打开对应数据库的服务。MySQL在Windows下的启动命令为
net start mysql
测试代码
复制代码
public static void main(String args[]) {
JDBCOperation.getAll();
JDBCOperation.insert(new Student("Achilles", "Male", "14"));
JDBCOperation.getAll();
JDBCOperation.update(new Student("Bean", "", "7"));
JDBCOperation.delete("Achilles");
JDBCOperation.getAll();
}
复制代码
Eclipse中的输出
复制代码
============================
1 Ender male 8
2 Bean male 6
3 Petra fema 9
4 Peter male 9
5 _Graff male 40
6 GOD fema 255
============================
============================
1 Ender male 8
2 Bean male 6
3 Petra fema 9
4 Peter male 9
5 _Graff male 40
6 GOD fema 255
7 Achilles Male 14
============================
resutl: 1
resutl: 1
============================
1 Ender male 8
2 Bean male 7
3 Petra fema 9
4 Peter male 9
5 _Graff male 40
6 GOD fema 255
============================
复制代码
三、代码分析
在上述对数据库进行增删改查的过程中,可以发现其共性部分,即通用的流程:
(1)创建Connection对象、SQL查询命令字符串;
(2)对Connection对象传入SQL查询命令,获得PreparedStatement对象;
(3)对PreparedStatement对象执行executeUpdate()或executeQurey()获得结果;
(4)先后关闭PreparedStatement对象和Connection对象。
可见,使用JDBC时,最常打交道的是Connection、PreparedStatement这两个类,以及select中的ResultSet类。查阅Java API手册可以了解其具体的意义和方法。
下面引用的Java API的资料出自http://download.oracle.com/technetwork/java/javase/6/docs/zh/api/index.html。
Connection
java.sql
接口 Connection
所有超级接口:
Wrapper
public interface Connectionextends Wrapper
与特定数据库的连接(会话)。在连接上下文中执行 SQL 语句并返回结果。
Connection 对象的数据库能够提供描述其表、所支持的 SQL 语法、存储过程、此连接功能等等的信息。此信息是使用 getMetaData 方法获得的。
PreparedStatemnt
java.sql
接口 PreparedStatement
所有超级接口:
Statement, Wrapper
所有已知子接口:
CallableStatement
public interface PreparedStatementextends Statement
表示预编译的 SQL 语句的对象。
SQL 语句被预编译并存储在 PreparedStatement 对象中。然后可以使用此对象多次高效地执行该语句。
常用方法
boolean execute()
在此 PreparedStatement 对象中执行 SQL 语句,该语句可以是任何种类的 SQL 语句。
ResultSet executeQuery()
在此 PreparedStatement 对象中执行 SQL 查询,并返回该查询生成的 ResultSet 对象。
int executeUpdate()
在此 PreparedStatement 对象中执行 SQL 语句,该语句必须是一个 SQL 数据操作语言(Data Manipulation Language,DML)语句,比如 INSERT、UPDATE 或 DELETE 语句;或者是无返回内容的 SQL 语句,比如 DDL 语句。
ResultSet
java.sql
接口 ResultSet
所有超级接口:
Wrapper
所有已知子接口:
CachedRowSet, FilteredRowSet, JdbcRowSet, JoinRowSet, RowSet, SyncResolver, WebRowSet
public interface ResultSetextends Wrapper
表示数据库结果集的数据表,通常通过执行查询数据库的语句生成。
0 0
- JDBC Request的用法
- jdbc的用法
- JDBC的PreparedStatement用法
- JDBC的典型用法
- JDBC的典型用法
- JDBC的典型用法
- JDBC的用法-1
- 关于JDBC用法的练习
- 关于JDBC用法的练习
- JDBC结果集的用法
- jdbc的最基本用法
- JDBC API的基本用法
- JDBC之PreparedStatement的用法
- JDBC中BLOB的用法
- JDBC缓存块的用法
- JDBC的基本用法-2
- JDBC用法
- 转两篇关于jdbc的用法的文章
- Linux文件权限及用户管理
- 二值图像连通区域标记法,两步法
- Mysql之数据类型
- poj2112(二分网络流)
- POI读取Excel
- jdbc的用法
- VC 中char 与 wchar_t的转换
- P1865 A % B Problem
- PHP 数组(array)自定义排序
- Log4j资料整合(1)
- easyui的datagrid里getSelections只能获取一行值
- PAT B1032. 挖掘机技术哪家强(20)
- 设计模式分类
- angularJS各种自定义服务的区别