JDBC连接mysql

/**
* Created by admin on 2017/1/28.
*/
import java.sql.*;

public class MySQL {
public static void main(String[] args){
// jdbc 驱动器, 需要自己下载驱动器,否则无法连接到数据库
String driver = "com.mysql.jdbc.Driver";
// 连接地址
String url = "jdbc:mysql://127.0.0.1:3306/china";
String user = "root";
String password = "admin";
try{
// 加载mysql 驱动
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, user, password);
if (!conn.isClosed()){
System.out.println("connect successfully!");
}
Statement statement = conn.createStatement();
String sql = "show databases;";
ResultSet res = statement.executeQuery(sql);
// String data = null;
while (res.next()){
System.out.println(res.first());
}
}
catch (ClassNotFoundException e){
System.out.println("connect fail can't not found driver");
e.printStackTrace();
}
catch (SQLException e){
e.printStackTrace();

}
}
}
posted @ 2017-07-20 23:31  晴天小猫  阅读(270)  评论(0编辑  收藏  举报