JDBC基本操作演示与实现
实现步骤
温馨提示:不要忘记导入所使用数据库的驱动jar包
最基本的实现步骤
- 注册驱动
- 获取连接Connection
- 得到执行Sql语句的对象Statement
- 执行sql语句,并返回结果
- 处理结果
- 关闭Connection(相当于断开连接)
按照上述步骤我们进行代码实现如下:
package com.immunize.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* 第一段JDBC代码
*
* @author Mr IMMUNIZE
*
*/
public class JDBC_test01 {
public static void main(String[] args) throws Exception {
// 注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取连接Connection
Connection cnn = DriverManager.getConnection("jdbc:mysql://localhost:3306/immunize1024", "root", "wbhsb");
// 得到执行Sql语句的对象Statement
Statement stmt = cnn.createStatement();
// 执行sql语句,并返回结果
ResultSet rs = stmt.executeQuery("select id,name,password,email,birthday from t_user");
// 处理结果
while (rs.next()) {
System.out.println(rs.getObject("id"));
System.out.println(rs.getObject("name"));
System.out.println(rs.getObject("password"));
System.out.println(rs.getObject("email"));
System.out.println(rs.getObject("birthday"));
System.out.println("------------");
}
// 关闭Connection(相当于断开连接)
rs.close();
stmt.close();
cnn.close();
}
}
这就是一段JDBC的调用的最简单代码,我们输出查询结果到Console面板显示如下:
1
tiger
123
tiger@163.com
1994-12-01
2
rabbit
123456
tiger@163.com
1997-06-11
3
sheep
123456
sheep@163.com
1995-07-15
5
cat
123456
cat@163.com
1992-12-01
6
cat
123456
cat@163.com
1992-12-01
与数据库的结果一致:
出现的问题及优化
出现的问题:
- 可以使用jdk7.0的新特性使关闭Connection的操作省略:将其放在try,catch语句块的try后面的小括号里来实现自动关闭。
- 为提高可维护性,我们可以将驱动,url,username,password等数据存放在一个db.properties的文件中,并提取为一个工具类DBUtil来实现对其的调用。
- 使用PreparedStatement类来取代Statement类,这是纯粹出于开发的考虑。
- 使用?占位符来取代字符串拼接导致的sql语句注入问题。
下面将以实例的形式呈现在完善后的版本
完善后的版本
- 将以登录功能的验证来对上述JDBC的代码进行完善和展示
//Login测试类
package com.immunize.jdbc.controller;
import java.util.Scanner;
import com.immunize.jdbc.bean.User;
import com.immunize.jdbc.service.LoginService;
/**
* 實現用戶登錄的功能
*
*/
public class Login {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("請輸入用戶名:");
String name = s.nextLine();
System.out.println("請輸入密碼:");
String password = s.nextLine();
LoginService ls = new LoginService();
User u = ls.findUserByNameAndPassword(name, password);
if (u == null) {
System.out.println("用戶名或密碼錯誤!");
} else {
System.out.println("登錄成功!");
}
}
}
//LoginService工具类
package com.immunize.jdbc.service;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.immunize.jdbc.bean.User;
import com.immunize.jdbc.util.DBUtil;
public class LoginService {
public User findUserByNameAndPassword(String name, String password) {
User u = null;
String sql = "select id,name,password,email,birthday from t_user where name=?and password=?";
try ( // 获取连接Connection
Connection cnn = DBUtil.getConnection();
// 得到执行Sql语句的对象Statement
PreparedStatement stmt = cnn.prepareStatement(sql);
// 执行sql语句,并返回结果
) {
stmt.setString(1, name);
stmt.setString(2, password);
try (ResultSet rs = stmt.executeQuery()) {
// 处理结果
while (rs.next()) {
u = new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
u.setPassword(rs.getString("password"));
u.setEmail(rs.getString("email"));
u.setBirthday(rs.getDate("birthday"));
}
System.out.println(rs);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return u;
}
}
//DBUtil类用于对封装好的Connection对象进行调用,使用到了getConnection方法
package com.immunize.jdbc.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;
public class DBUtil {
private static String driverClass;
private static String url;
private static String username;
private static String password;
static {
ResourceBundle rb = ResourceBundle.getBundle("db");
driverClass = rb.getString("driverClass");
url = rb.getString("url");
username = rb.getString("username");
password = rb.getString("password");
try {
// 注册驱动
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
}
//db.properties文件
url = jdbc:mysql://localhost:3306/immunize1024
driverClass = com.mysql.jdbc.Driver
username = root
password = wbhsb
//User类
package com.immunize.jdbc.bean;
import java.util.Date;
//java.sql.Date实际是继承了java.util.Date的。
/**
* @author Mr IMMUNIZE
*
*/
public class User {
private int id;
private String name;
private String password;
private String email;
private Date birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password + ", email=" + email + ", birthday="
+ birthday + "]";
}
}
到此就完成了对数据库的登录功能的实现与测试。
以上记录仅供记录与学习交流!