import java.sql.*
;
2
3 public class MysqlTest
4 {
5 public static void main(String[] args)
throws SQLException,ClassNotFoundException{
6 // TODO Auto-generated method stub
7
8 String url = "jdbc:mysql://localhost/xh"
;
9 String username = "xiaohengdada"
;
10 String password = "123456"
;
11 //DriverManager.registerDriver(new com.mysql.jdbc.Driver());
12
13 Class.forName("org.gjt.mm.mysql.Driver"
);
14
15 Connection connection =
DriverManager.getConnection(url,username,password);
16
17 Statement stat =
connection.createStatement();
18
19
20 // 执行查找操作
21 ResultSet rsResultSet = stat.executeQuery("select * from students"
);
22
23 while (rsResultSet.next()) {
24 System.out.println("id = "+ rsResultSet.getObject("id"
));
25 System.out.println("name = "+ rsResultSet.getObject("name"
));
26 System.out.println("sex = "+ rsResultSet.getObject("sex"
));
27 System.out.println("age = "+ rsResultSet.getObject("age"
));
28 }
29
30 // 执行更新操作
31 String sql = "update students set name = ‘xiaoheng‘ where name = ‘Ender‘"
;
32 System.out.println(sql);
33 int statentnum =
stat.executeUpdate(sql);
34 System.out.println(statentnum);
35 if (statentnum>0
) {
36 System.out.println("update ok"
);
37 }
38
39 // 执行删除操
40 sql = "delete from students where name = ‘Peter‘"
;
41 System.out.println(sql);
42 statentnum =
stat.executeUpdate(sql);
43 System.out.println(statentnum);
//为什么这里输出的结果为0
44 if (statentnum>0
) {
45 System.out.println("delete ok"
);
46 }
47
48 //执行插入操作
49 sql="insert into students values(8,‘nimeide‘,‘fema‘,‘255‘)"
;
50 System.out.println(sql);
51 statentnum =
stat.executeUpdate(sql);
52 System.out.println(statentnum);
//为什么这里输出的结果为0
53 if (statentnum>0
) {
54 System.out.println("insert ok"
);
55 }
56
57 // 资源的释放
58 rsResultSet.close();
59 stat.close();
60 connection.close();
61 }
62 }

上面相当于普通的交互过程,每处理一条数据,就需要访问一次数据库。
故可采用批处理和事务来进行处理。
批处理:累积到一定数量,再一次性提交到数据库,减少了与数据库的交互操作,所以效率会提高。
事务:事务指逻辑上的一组操作,组成这组操作的各个单元,要么全部成功,要么全部不成功,默认是关闭事务的。
SQL 注入的防范
SQL 注入是用户利用某些系统没有对输入数据进行充分的检查,从而进行恶意破坏的行为。
1、statement存在sql注入攻击问题,例如登陆用户名采用‘ or 1=1 or username=‘
2、对于防范 SQL 注入,可以采用PreparedStatement取代Statement。
PreparedStatement
PreperedStatement是Statement的孩子,它的实例对象可以通过调用Connection.preparedStatement()方法获得,相对于Statement对象而言的优势:
(1) 防止SQL注入:PreperedStatement可以避免SQL注入的问题。
(2) 预编译SQL语句:Statement会使数据库频繁编译SQL,可能造成数据库缓冲区溢出。PreparedStatement 可对SQL进行预编译,从而提高数据库的执行效率。
(3) 使用占位符简化语句:并且PreperedStatement对于sql中的参数,允许使用占位符的形式进行替换,简化sql语句的编写。 (例如多次循环插入数据)
java连接mysql(一)
标签: