jdbc总结
jdbc
1. 连接数据库的步骤:
1) 注册驱动
2) 建立连接
3) 创建语句
4) 执行语句
5) 处理结果
6) 释放资源(注意关闭的顺序)
实例//1.注册驱动
[java]
DriverManager.registerDriver(newcom.mysql.jdbc.Driver());
System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver");//推荐方式
//2.建立连接
String url = "jdbc:mysql:localhost:3306/jdbc";
String user = "root";
String password = "mysql";
Connection conn = DriverManager.getConnection(url,user,password);
//3.创建语句
Statement st = conn.createStatement();
//4.执行语句
ResultSet rs = st.executeQuery("select * from user");
//5.处理结果
while(rs.next()){//按行来遍历
System.out.println(rs.getObject(1) + "\t" + rs.getObject(2) + "\t" +rs.getObject(3) + "\t" + rs.getObject(4));
}
//6.释放资源(注意关闭的顺序)
rs.close();
st.close();
conn.close();
2. 注意在jdbc中的sql注入问题,解决的办法是使用PreparedStatement :PreparedStatement ps = null;// 利用PreparedStatement而不用Statement是因为PreparedStatement能够对输入的内容进行过滤,除去sql的关键字,防止此问题。
3. 数据库中对大文本的写入和读取:clob类的处理
[java]
public class ClobTest {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//create();
read();
}
//数据库的读取操作
static void read() throws SQLException, Exception {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
// 3.创建语句
st = conn.createStatement();
// 4.执行语句
rs = st.executeQuery("select big_text from clob_test");
// 5.处理结果
while (rs.next()) {// 按行来遍历
Reader reader = rs.getCharacterStream(1);
Filefile = newFile("CRUD_bak.java");
Writerwriter = new BufferedWriter(new FileWriter(file));
char[] buff = new char[1024];
for(int i = 0; (i = reader.read(buff))>0;){
writer.write(buff,0, i);
}
writer.close();
reader.close();
}
} finally {
JdbcUtils.free(rs, st, conn);
}
}
//数据库的创建操作
static void create() throws SQLException, IOException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
// 3.创建语句
String sql = "insertinto clob_test(big_text) values(?)";
ps = conn.prepareStatement(sql);
File file = new File("src/com/lcq/jdbc/CRUD.java");
Reader reader = newBufferedReader(newFileReader(file));
//传递大块的文本文档
ps.setCharacterStream(1,reader, file.length());
int i = ps.executeUpdate();
reader.close();
System.out.println("i = " + i);
} finally {
JdbcUtils.free(rs, ps, conn);
}
}
}
4. 问题blob类型读取二
补充:软件开发 , Java ,