欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 运维知识 > 数据库 >内容正文

数据库

相对完善的Java通过JDBC操纵mysql的例子

发布时间:2023/12/4 数据库 44 豆豆
生活随笔 收集整理的这篇文章主要介绍了 相对完善的Java通过JDBC操纵mysql的例子 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

工具类:

 

Code
 1import java.sql.Connection;
 2import java.sql.DriverManager;
 3import java.sql.ResultSet;
 4import java.sql.SQLException;
 5import java.sql.Statement;
 6
 7
 8public final class JDBCUtils {
 9
10    private JDBCUtils(){}
11    
12    private static String url="jdbc:mysql://localhost:3306/forum";
13    private static String user="root";
14    private static String password="root";
15    
16    static{
17        try {
18            Class.forName("com.mysql.jdbc.Driver");
19        }
 catch (ClassNotFoundException e) {
20            throw new ExceptionInInitializerError(e);
21        }

22    }

23    
24    public static Connection getConnection() throws SQLException
25    {
26        return DriverManager.getConnection(url, user, password);        
27    }

28    
29    public static void free(ResultSet rs,Statement st,Connection conn)
30    {
31        try{
32            
33            if(rs!=null)
34                rs.close();
35        }
catch(SQLException e){
36            e.printStackTrace();
37        }
finally{
38            
39                        try{
40                            if(st!=null)
41                                st.close();
42                        }
catch(SQLException e){
43                            e.printStackTrace();
44                        }
finally{
45                            
46                                        try{
47                                            if(conn!=null)
48                                                conn.close();
49                                        }
catch(SQLException e){
50                                            e.printStackTrace();
51                                        }
        
52                        }

53        }

54    }

55}

56

使用的例子:

 

Code
 1public static void main(String[] args) {
 2        // TODO Auto-generated method stub
 3        try {
 4            JDBCUtilsTest();
 5        }
 catch (Exception e) {
 6            // TODO Auto-generated catch block
 7            e.printStackTrace();
 8        }

 9
10    }

11    
12    
13    public static void JDBCUtilsTest() throws Exception
14    {
15        Connection conn=null;
16        Statement st=null;
17        ResultSet rs=null;
18        
19        try{
20            conn=JDBCUtils.getConnection();
21            st=conn.createStatement();
22            rs=st.executeQuery("select * from user");
23            while(rs.next())
24            {
25                System.out.println(rs.getObject(1)+"\t"+rs.getObject(2));
26            }

27        }
finally{
28            JDBCUtils.free(rs, st, conn);
29        }
    
30        
31    }

转载于:https://www.cnblogs.com/sousou/archive/2009/01/20/1379102.html

总结

以上是生活随笔为你收集整理的相对完善的Java通过JDBC操纵mysql的例子的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。