一、如何实现java和数据库连接
1.下载驱动类jar文件,在项目目录下创建文件夹叫lib,将jar文件复制到lib下,右键点击Build Path就配置完成了。
2.实现java和数据库连接分为六步:
加载驱动类
创建链接
获取执行对象
执行sql语句
解析结果
关闭连接
代码如下:
package com.jdbc;
import java.sql.*;
public class Easy {
public static void main(String[] args) throws ClassNotFoundException,SQLException{
//加载驱动类
Class.forName("com.mysql.cj.jdbc.Driver");
//创建连接
String url="jdbc:mysql://localhost:3306/mydata?useSSL=false&characterEncoding=utf8";
String user="root";
String password="123456";
Connection con=DriverManager.getConnection(url, user, password);
//获取执行对象
Statement sta=con.createStatement();
String sql="insert into t_log values ('JDBC')";
//执行sql语句
int count=sta.executeUpdate(sql);//
//解析结果
System.out.println(count);
//关闭连接
sta.close();
con.close();
}
}
以防报错,添加上报错处理
package com.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Easy2 {
public static void main(String[] args) {
//连接对象声明
Connection con=null;
//执行对象的声明
Statement sta=null;
try {
//加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/mydata?useSSL=false&characterEncoding=utf8";
String user="root";
String password="123456";
con=DriverManager.getConnection(url, user, password);
//获取执行对象
sta=con.createStatement();
String sql="delete from t_log";
//执行sql语句
int count=sta.executeUpdate(sql);
//解析执行结果
System.out.println(count);
}catch(Exception e) {
//打印异常信息
e.printStackTrace();
}finally {
if(sta!=null) {
//只有sta不等于null时,尝试关闭
try {
sta.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con!=null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
3.查询方法的解析:
package com.jdbc;
import java.lang.reflect.Field;
public class Easy5 {
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
//Class 描述类怎样定义的
//获取类对象
Class clazz=Student.class; //获取类的类对象
//只能找到返回public修饰的属性
//clazz.getField("sid");
//获取任意访问权限修饰的属性
Field f=clazz.getDeclaredField("sid");
f.setAccessible(true);
Student stu=new Student();
f.set(stu, "张三");
System.out.println(stu);
Field[] f_arr=clazz.getDeclaredFields();//获取类中的所有的属性
for(Field fie:f_arr) {
fie.setAccessible(true);
String f_name=fie.getName();
System.out.println(f_name);
}
// clazz.getMethods();//获取类中定义的方法
}
}
4.查询方法的运用
package com.jdbc;
import java.util.List;
public class Easy4 {
public static void main(String[] args) {
String sql="select * from student";
Class stuClass=Student.class;
List list=JDBC.query(sql,stuClass);
for(Object obj:list) {
System.out.println(obj);
}
}
}
5.JDBC类的封装
package com.jdbc;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class JDBC {
private static Connection con=null;
private static Statement sta=null;
private static ResultSet rs=null;
static {
try {
//文件路径
//项目路径
String filePath=System.getProperty("user.dir")+"\\src\\jdbc.properties";
FileInputStream fis=new FileInputStream(filePath);
Properties prop=new Properties();
prop.load(fis);
//从文件中读取属性
String driverClassName=prop.getProperty("driverClassName");
String url=prop.getProperty("url");
String username=prop.getProperty("username");
String userpass=prop.getProperty("userpass");
//将外部信息放到配置文件中
Class.forName(driverClassName);
con=DriverManager.getConnection(url,username,userpass);
sta=con.createStatement();
}catch(Exception e) {
e.printStackTrace();
}
}
/**
* 创建连接对象
*/
public static Connection getConnection() throws ClassNotFoundException,SQLException{
Connection con=null;
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydata?useSSL=false&characterEncoding=utf8";
String user = "root";
String password = "123456";
con=DriverManager.getConnection(url, user, password);
return con;
}
/**
* 获取执行对象
* @param con
* @return
* @throws SQLException
*/
public static Statement getStatement(Connection con) throws SQLException{
Statement sta=null;
sta=con.createStatement();
return sta;
}
//增添删
public static int update(String sql) {
int result=0;
try {
result=sta.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
//查
public static List query(String sql,Class clazz) {
List list=new ArrayList();
try {
rs=sta.executeQuery(sql);
//获取类对象中所有的属性
Field[] f_arr=clazz.getDeclaredFields();
//设置所有属性可访问
for(Field f:f_arr) {
f.setAccessible(true);
}
//解析结果集-- 循环数据库的结果集
while(rs.next()){
//一行数据就是一个对象(Class指定的对象)
//实例化对象
Object obj=clazz.newInstance();
for(Field f:f_arr) {
String fname=f.getName();//属性名
Object data=rs.getObject(fname);
f.set(obj, data);
}
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* 关闭连接
* @param sta
* @param con
*/
public static void close() {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(sta!=null) {
try {
sta.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con!=null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
///**
// * 新增数据
// * @param sta
// * @param sql
// * @return
// * @throws SQLException
// */
//public static int insert(Statement sta,String sql) throws SQLException {
// return sta.executeUpdate(sql);
//}
///**
// * 新增
// * @param sql
// * @return
// */
//public static int insert(String sql) {
// int result=0;
// try {
// result=sta.executeUpdate(sql);
// } catch (SQLException e) {
// e.printStackTrace();
// }
// return result;
//}
///**
// * 修改数据
// * @param sta
// * @param sql
// * @return
// * @throws SQLException
// */
//public static int update(Statement sta,String sql) throws SQLException {
// return sta.executeUpdate(sql);
//}
///**
// * 修改
// * @param sql
// * @return
// */
//public static int update(String sql) {
// int result=0;
// try {
// result=sta.executeUpdate(sql);
// } catch (SQLException e) {
// e.printStackTrace();
// }
// return result;
//}
///**
// * 删除数据
// * @param sta
// * @param sql
// * @return
// * @throws SQLException
// */
//public static int delete(Statement sta,String sql) throws SQLException {
// return sta.executeUpdate(sql);
//}
///**
// * 删除
// * @param sql
// * @return
// */
//public static int delete(String sql) {
// int result=0;
// try {
// result=sta.executeUpdate(sql);
// } catch (SQLException e) {
// e.printStackTrace();
// }
// return result;
//}
6.预编译执行对象 PreparedStatement
将sql语句进行预先编译,确定sql语句结构,可以防止sql注入
?代表占位符 1...5设置参数,设置进来的参数不会改变sql语句的语义
static void test2(String sid) throws Exception {
Connection con=JDBC.getConnection();
String sql="select * from student where sid=?";
//对sql语句进行预先编译,确定sql语句的结构
//可以防止sql注入
PreparedStatement psta=con.prepareStatement(sql);
psta.setInt(1,345);
ResultSet rs=psta.executeQuery();
int i=0;
while(rs.next()) {
i++;
}
System.out.println(i);
psta.close();
JDBC.close();
}