JDBC概述

JDBC
1.JDBC javas database connectivity java数据库的连接

2.jdbc的操作步骤
第一:加载数据库驱动
Class.forName(com.mysql.jdbc.Driver);

第二:创建连接
Connection conn = 
DriverManager.getConnection("jdbc:mysql//localhost:3307/数据表名称","登录数据库用户名","登录密码");

第三:编写sql语句
String sql = "select * from user";

第四:执行sql语句
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);

第五:遍历结果集,得到每一条记录
while(rs..next()){
System.out.println(re.getString("username") + " : " + re.getInt("age"));
}

第六:释放资源
rs.close();
stmt.close();
conn.close();

3.jdbc的Statement对象
执行查询
ResultSet executQuery(sql) 返回查询结果集

执行增删改
int executeUpdate(sql) 返回成功的记录

执行批处理的方法
addBatch(String sql):把多个sql语句放到批处理里面
int[] executeBatch():执行批处理里面的所有的sql

4.释放资源:
finally {
//释放资源
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}

if(stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}

if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}


5.JDBC的工具封装类
用properties格式文件存储数据库信息文件

第一种,使用properties类
public static String driverName;
public static String url;
public static String username;
public static String password;

static{
try {
Properties p = new Properties();
InputStream in = new FileInputStream("db.properties");
p.load(in);
driverName=p.getProperty("driverName");
url=p.getProperty("url");
username=p.getProperty("username");
password=p.getProperty("password");
} catch (Exception e) {
e.printStackTrace();
}
}

第二种,使用ResourceBoundle类
driverName = ResourceBoundle.getBoundle(db).getString("driverName");
url = RsourceBoundle.getBoundle(db).getString("url");
username = ResourceBundle.getBundle("db").getString("username");
password = ResourceBundle.getBundle("db").getString("password");


6.sql注入与防止
注入:在登录是输入bbb' or '1=1,因为存在bbb用户,由于or的条件只要有一个成立登录了

防止sql注入
使用PreparedStatement预编译对象就能防止sql注入

代码
//使用工具类得到数据库连接
conn = JDBC.getConnection();

编写sql
String sql = "select * from user where username=? and password=?";

对sql进行预编译
pstmt = conn.prepareStatement(sql);

s设置参数 
pstmt.setString(1,name);
pstmt.setString(2,pasw);

执行sql
pstmt.excuteQuery();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值