jdbc操作mysql数据库

       

JDBC操作mysql操作的步骤

       1.      注册驱动

  2.      建立连接

  3.      创建执行sql语句的对象

  4.      执行语句

  5.      处理执行结果

  6.      释放资源

 1 package com.jdbc.test;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.ResultSet;
 6 import java.sql.SQLException;
 7 import java.sql.Statement;
 8 
 9 
10 /**
11  * jdbc操作mysql数据库
12  * @author 
13  *
14  */
15 public class JDBCTest {
16 
17     public static void main(String[] args) {
18        //数据库的驱动
19        String driver="com.mysql.jdbc.Driver";
20        //连接的数据库
21        String url="jdbc:mysql://127.0.0.1:3306/test";
22        //数据库的连接账号
23        String username="root";
24        //数据库的密码
25        String password="000000";
26        Connection conn=null;
27        Statement st=null;
28        ResultSet rs=null;
29        try {
30         //注册数据库驱动 (加载成功后会将Driver类的实例注册到DriverManager中)  
31         Class.forName(driver);
32         //获取数据库连接
33         conn=DriverManager.getConnection(url,username,password);
34         //获取数据库操作对象
35         st=conn.createStatement();
36         //编写操作的Sql语句
37         String sql="select * from ceshi";
38         //执行数据库操作
39         rs=st.executeQuery(sql);
40         //获取操作数据库的到的结果集并操作
41         while(rs.next()) {
42             System.out.print(rs.getInt("id"));
43             System.out.print(rs.getString("username"));
44             System.out.print(rs.getString("age"));
45             System.out.println("\n");
46         }
47         
48         } catch (Exception e) {
49             e.printStackTrace();
50         }finally {      //关闭对象回,收数据库资源
51         
52             if(rs!=null) {  //关闭结果集对象
53                 try {
54                     rs.close();
55                 } catch (SQLException e) {
56                     e.printStackTrace();
57                 }
58             }
59             
60             if(st!=null) {  //关闭数据库操作对象
61                 try {
62                     st.close();
63                 } catch (SQLException e) {
64                     e.printStackTrace();
65                 }
66             }
67             
68             if(conn!=null) {  //关闭数据库连接对象
69                 try {
70                     if(!conn.isClosed()) {
71                         conn.close();
72                     }
73                 } catch (SQLException e) {
74                     e.printStackTrace();
75                 }
76             }
77         }
78     }
79     
80 }

猜你喜欢

转载自www.cnblogs.com/liusha-1/p/12822885.html
今日推荐