Java实现JDBC连接数据库实例

 1 import java.sql.Connection;
 2 import java.sql.DriverManager;
 3 import java.sql.ResultSet;
 4 import java.sql.SQLException;
 5 import java.sql.Statement;
 6 
 7 public class JDBCTest {
 8     
 9     private static final String URL="jdbc:mysql://127.0.0.1:3306/student";
10     private static final String USER="root";
11     private static final String PASSWORD="root";
12 
13     public static void main(String[] args) throws ClassNotFoundException, SQLException {
14         
15         //1.加载驱动程序
16         Class.forName("com.mysql.jdbc.Driver");
17         
18         //2.获得数据连接
19         Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
20         
21         //3.使用数据库的连接创建声明
22         Statement stmt = conn.createStatement();
23         
24         //4.使用声明执行SQL语句
25         ResultSet rs = stmt.executeQuery("select * from stu");
26         
27         //5.读取数据库的信息
28         while(rs.next()){
29             String id = rs.getString("id");
30             String name = rs.getString("name");
31             String sex = rs.getString("sex");
32             String score = rs.getString("score");
33             System.out.println(id+"姓名:"+name+",性别:"+sex+",成绩:"+score);
34         }
35 
36     }
37     
38 }

 

posted @ 2016-09-22 11:54  Web1024  阅读(597)  评论(0编辑  收藏  举报