先祝能看到这篇博客的同学狗年大吉大利,大年初一我这里就下雨了,可谓好雨知时节,当春乃发生。
这几天琐事甚多,今天给大家更新一篇博客,关于jdbc连接数据库的操作,还是蛮重要的。
1 jdbc连接数据库
package cn.itheima.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
/**
* 测试sql注入问题
* @author Wl
*
*/
public class TestLogin {
@Test
public void testLogin(){
}
/**
* 用户登录方法
* @param usename
* @param password
* @throws ClassNotFoundException
* @throws SQLException
*/
public void login(String usename,String password) throws ClassNotFoundException, SQLException{
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/web08","root","root");
//3.创建执行sql语句对象
Statement stmt = conn.createStatement();
//4.书写一个sql语句
String sql = "select * from tbl_user where "+"uname='"+usename+"' and upassword='"+password+"'";
//5.执行sql语句
ResultSet rs = stmt.executeQuery(sql);
//6.对结果集进行处理
if(rs.next()){
System.out.println("恭喜您,"+usename+",登陆成功!");
System.out.println(sql);
}else{
System.out.println("账号或密码错误!");
}
//7.关闭资源
if(rs!=null) rs.close();
if(stmt!=null) stmt.close();
if(conn!=null) conn.close();
}
public void login1(String usename,String password) throws ClassNotFoundException, SQLException{
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/web08","root","root");
//3.编写sql语句
String sql = "select * from tbl_user where uname=? and upassword=?";
//4.创建预处理对象
PreparedStatement pstmt = conn.prepareStatement(sql);
//5.给占位符设置参数
pstmt.setString(1, usename);
pstmt.setString(2, password);
//6.执行查询操作
ResultSet rs = pstmt.executeQuery();
//7.对结果集进行处理
if (rs.next()) {
System.out.println("恭喜您," + usename + ",登陆成功!");
System.out.println(sql);
} else {
System.out.println("账号或密码错误!");
}
//8.关闭资源
if (rs != null)rs.close();
if (pstmt != null)pstmt.close();
if (conn != null)conn.close();
}
}
注释:以上就是jdbc连接数据库的7个步骤,这里有几点问题说明一下
(1)连接mysql数据库需要导jar包,没有或者不会的同学,可以加我qq询问2651164672;
(2)程序书写过程任何地方需要导包的请导入java.sql包,不要导入mysql.sql包,这是初学者极其容易犯的错误;
(3)上面程序中有两个方法第一个中用statement处理语句,第二个用preparedstatement处理,二者有何区别呢,请记住第二个叫做预编译处理对象,可以防止sql注入问题,至于sql注入问题,此处不再赘述,知道以后只用preparedstatement对象即可。
2 抽取JDBC工具类
2.1 版本一
package cn.itheima.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 提供获取连接和释放资源的方法
* @author Wl
*
*/
public class JDBCUtils_v1 {
/**
* 获取连接方法
* @return
*/
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/web09", "root", "root");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void release(Connection conn,PreparedStatement pstmt,ResultSet rs){
if(rs!=null)
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(pstmt!=null)
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2.2 版本二
package cn.itheima.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;
/**
* 提供获取连接和释放资源的方法
* @author Wl
*
*/
public class JDBCUtils_v2 {
private static String driver;
private static String url;
private static String usename;
private static String password;
/**
* 静态代码块加载配置文件信息
*/
static{
ResourceBundle bundle = ResourceBundle.getBundle("db");
driver = bundle.getString("driver");
url = bundle.getString("url");
usename = bundle.getString("usename");
password = bundle.getString("password");
}
/**
* 获取连接方法
* @return
*/
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,usename,password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void release(Connection conn,PreparedStatement pstmt,ResultSet rs){
if(rs!=null)
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(pstmt!=null)
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2.3 版本三
package cn.itheima.jdbc;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.ResourceBundle;
/**
* 提供获取连接和释放资源的方法
* @author Wl
*
*/
public class JDBCUtils_v3 {
private static String driver;
private static String url;
private static String usename;
private static String password;
/**
* 静态代码块加载配置文件信息
*/
static{
try {
//1.通过当前类获取类加载器
ClassLoader loader = JDBCUtils_v3.class.getClassLoader();
//2.通过类加载器的一个方法获得一个输入流
InputStream inputStream = loader.getResourceAsStream("db.properties");
//3.创建一个properties对象
Properties props = new Properties();
//4.加载输入流
props.load(inputStream);
//5.获取相关参数
driver = props.getProperty("driver");
url = props.getProperty("url");
usename = props.getProperty("usename");
password = props.getProperty("password");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取连接方法
* @return
*/
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,usename,password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void release(Connection conn,PreparedStatement pstmt,ResultSet rs){
if(rs!=null)
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(pstmt!=null)
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
以上三个版本的区别在于细节处理,下一次会提供不仅节省代码而且节约数据库资源的代码。
下面是测试所用的代码
package cn.itheima.jdbc.test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.Test;
import cn.itheima.jdbc.JDBCUtils_v1;
import cn.itheima.jdbc.JDBCUtils_v2;
import cn.itheima.jdbc.JDBCUtils_v3;
/**
* 测试工具类
* @author Wl
*
*/
public class TestUtils {
/**
* 根据id修改数据
*/
@Test
public void testUpdateById(){
Connection conn = null;
PreparedStatement pstmt = null;
try {
//1.获取连接
conn = JDBCUtils_v3.getConnection();
//2.编写sql语句
String sql = "update user set name=? where id=?";
//3.编写执行sql语句对象
pstmt = conn.prepareStatement(sql);
//4.设置参数
pstmt.setString(1, "前女友");
pstmt.setInt(2, 2);
//5.执行删除操作
int row = pstmt.executeUpdate();
if(row > 0){
System.out.println("更新成功!");
}else{
System.out.println("更新失败!");
}
} catch (Exception e) {
new RuntimeException(e);
} finally{
//6.释放资源
JDBCUtils_v3.release(conn, pstmt, null);
}
}
/**
* 根据id删除数据
*/
@Test
public void testDeleteById(){
Connection conn = null;
PreparedStatement pstmt = null;
try {
//1.获取连接
conn = JDBCUtils_v3.getConnection();
//2.编写sql语句
String sql = "delete from user where id=?";
//3.编写执行sql语句对象
pstmt = conn.prepareStatement(sql);
//4.设置参数
pstmt.setInt(1, 2);
//5.执行删除操作
int row = pstmt.executeUpdate();
if(row > 0){
System.out.println("删除成功!");
}else{
System.out.println("删除失败!");
}
} catch (Exception e) {
new RuntimeException(e);
} finally{
//6.释放资源
JDBCUtils_v3.release(conn, pstmt, null);
}
}
/**
* 添加商品信息
*/
@Test
public void testAdd(){
Connection conn = null;
PreparedStatement pstmt = null;
try {
//1.获取连接
conn = JDBCUtils_v2.getConnection();
//2.编写sql语句
String sql = "insert into product values(?,?,?,?)";
//3.获取执行sql语句对象
pstmt = conn.prepareStatement(sql);
//4.设置参数
pstmt.setString(1, "p011");
pstmt.setString(2, "海带汤");
pstmt.setDouble(3, 0.1);
pstmt.setString(4, "c003");
//5.执行操作
int row = pstmt.executeUpdate();
if(row > 0){
System.out.println("插入成功!");
}else{
System.out.println("插入失败!");
}
} catch (Exception e) {
new RuntimeException(e);
} finally{
//6.释放资源
JDBCUtils_v2.release(conn, pstmt, null);
}
}
/**
* 根据pid查询商品信息
*/
@Test
public void testFindUserById(){
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
//1.获取连接
conn = JDBCUtils_v1.getConnection();
//2.编写sql语句
//String sql = "select * from product where pid=?";
String sql = "select * from product";
//3.获取执行sql语句对象
pstmt = conn.prepareStatement(sql);
//4.设置参数
//pstmt.setString(1, "p001");
//5.执行查询操作
rs = pstmt.executeQuery();
//6.处理结果集
while(rs.next()){
System.out.println(rs.getString("pname")+"-----"+rs.getDouble("price"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally{
JDBCUtils_v1.release(conn, pstmt, rs);
}
}
}