这里做了一个JDBC连接MYSQL数据库的例子,其实JDBC代码基本上写了一次就不会变了,但是大家一定要把要变的驱动分离出来,这里我写死了,有兴趣可以看看!
代码
1. package com.jdbc;
2.
3. import java.sql.Connection;
4. import java.sql.DriverManager;
5. import java.sql.PreparedStatement;
6. import java.sql.ResultSet;
7.
8. /**
9. * JDBC实现MYSQL数据库连接,防止了SQL注入
10. * @author Administrator
11. *
12. */
13. public class JDBCExample {
14.
15. public JDBCExample(){
16. try {
17. this.setConnection();
18. } catch (Exception e) {
19. e.printStackTrace();
20. }
21. }
22.
23.
24. private static final String CLASS = "org.gjt.mm.mysql.Driver"; //驱动类
25. private static final String DRIVER = "jdbc:mysql://localhost:3306/test"; //驱动
26. private static final String USERNAME = "root"; //数据库用户名
27. private static final String PWD = ""; //数据库密码
28.
29. private Connection conn = null;
30. private PreparedStatement ps = null;
31. private ResultSet rs = null;
32.
33. /**
34. * 获取连接对象
35. * @return
36. * @throws Exception
37. */
38. public Connection setConnection() throws Exception{
39.
40. Class.forName(CLASS);
41. conn = DriverManager.getConnection(DRIVER,USERNAME,PWD);
42.
43. return conn;
44. }
45.
46. /**
47. * 查询操作(一般项目不是返回ResultSet,一般返回集合或对象)
48. * @param sql
49. * @param pare
50. * @return
51. * @throws Exception
52. */
53. public ResultSet query(String sql,Object[] pare) throws Exception{
54.
55. ps = conn.prepareStatement(sql);
56. //设置参数
57. for(int i = 0; i<pare.length; i++){
58. ps.setObject(i+1, pare[i]);
59. }
60. rs = ps.executeQuery();
61.
62. return rs;
63. }
64.
65. /**
66. * 增删改操作
67. * @param sql
68. * @param pare
69. * @return
70. * @throws Exception
71. */
72. public int edit(String sql,Object[] pare) throws Exception{
73.
74. int hasEffect = 0; //影响行数
75. ps = conn.prepareStatement(sql);
76. //设置参数
77. for(int i = 0; i<pare.length; i++){
78. ps.setObject(i+1, pare[i]);
79. }
80. hasEffect = ps.executeUpdate();
81. return hasEffect;
82. }
83.
84. /**
85. * 关闭所有对象
86. * @throws Exception
87. */
88. public void closeAll() throws Exception{
89.
90. if(rs != null){
91. rs.close();
92. }if(ps != null){
93. ps.close();
94. }if(conn != null){
95. conn.close();
96. }
97. }
98.
99. /**
100. * 测试
101. * @param args
102. */
103. public static void main(String[] args) {
104. JDBCExample test = new JDBCExample();
105. }
106.
107. }


浙公网安备 33010602011771号