连接数据库
                        
                            时间:2021-07-01 10:21:17
                            帮助过:3人阅读
							                        
                     
                    
                    
                     public class connectionDB {
 2      public static void main(String[] args) {
 3             //声明Connection对象
 4             Connection con;
 5             //驱动程序名
 6             String driver = "com.mysql.jdbc.Driver"
;
 7             //URL指向要访问的数据库名mydata
 8             String url = "jdbc:mysql://localhost:3306/bbs"
;
 9             //MySQL配置时的用户名
10             String user = "root"
;
11             //MySQL配置时的密码
12             String password = "root"
;
13             //遍历查询结果集
14             try {
15                 //加载驱动程序
16                 Class.forName(driver);
17                 //1.getConnection()方法,连接MySQL数据库!!
18                 con =
 DriverManager.getConnection(url,user,password);
19                 if(!
con.isClosed())
20                     System.out.println("Succeeded connecting to the Database!"
);
21                 //2.创建statement类对象,用来执行SQL语句!!
22                 Statement statement =
 con.createStatement();
23                 //要执行的SQL语句
24                 String sql = "select * from user"
;
25                 //3.ResultSet类,用来存放获取的结果集!!
26                 ResultSet rs =
 statement.executeQuery(sql);32                  
33                 String name = 
null;
34                 String id = 
null;
35                 while(rs.next()){
36                     //获取stuname这列数据
37                     name = rs.getString("id"
);
38                     //获取stuid这列数据
39                     id = rs.getString("name"
);
40 
41                     //输出结果
42                     System.out.println(id + "\t" +
 name);
43                 }
44                 rs.close();
45                 con.close();
46             } 
catch(ClassNotFoundException e) {   
47                 //数据库驱动类异常处理
48                 System.out.println("Sorry,can`t find the Driver!"
);   
49                 e.printStackTrace();   
50                 } 
catch(SQLException e) {
51                 //数据库连接失败异常处理
52                 e.printStackTrace();  
53                 }
catch (Exception e) {
54                 // TODO: handle exception
55                 e.printStackTrace();
56             }
finally{
57                 System.out.println("数据库数据成功获取!!"
);
58             }
59         }
60 }
 
连接数据库
标签:bsp   url   ack   需要   sel   处理   stat   public   sele