1.需要下载JDBC驱动:
mysql-connector-java-5.0.5.zip
2.连接
// 驱动程序名
String driver = "com.mysql.jdbc.Driver";
// URL指向要访问的数据库名scutcs
String url = "jdbc:mysql://127.0.0.1:3306/scutcs";
// MySQL配置时的用户名
String user = "root";
// MySQL配置时的密码
String password = "root";
try {
// 加载驱动程序
Class.forName(driver);
// 连续数据库
Connection conn = DriverManager.getConnection(url, user, password);
if(!conn.isClosed())
System.out.println("Succeeded connecting to the Database!");
// statement用来执行SQL语句
Statement statement = conn.createStatement();
// 要执行的SQL语句
String sql = "select * from student";
// 结果集
ResultSet rs = statement.executeQuery(sql);
String name = null;
while(rs.next()) {
System.out.println(rs.getString("sno"));
}
rs.close();
conn.close();
} catch(ClassNotFoundException e) {
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch(SQLException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}