testjdbc.java
import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class testjdbc {
static final String DB_URL = "jdbc:mysql://10.47.12.205:3306/mysql?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true";
//注意:useSSL=true / false
// MySQL的JDBC URL编写方式:jdbc:mysql://主机名称:连接端口/数据库的名称
static final String USER = "root";
static final String PASS = "jetflow123";
public static void main(String[] args) throws SQLException,Exception{
Connection conn = null;
Statement stat = null;
// 注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 创建链接
conn = (Connection) DriverManager.getConnection(DB_URL,USER,PASS);
// 执行查询
stat = conn.createStatement();
String sql = "SELECT * FROM user";
ResultSet rs = stat.executeQuery(sql);
// 输出查询结果
while(rs.next()){
System.out.print(rs.getString("Host")+",");
System.out.print(rs.getString("User")+",");
System.out.print("\n");
}
// 关闭
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (stat != null) {
stat.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
connect.java
import java.sql.*;
public class conn {
public static void main(String[] args) {
String driver = "com.mysql.jdbc.Driver";
String URL = "jdbc:mysql://10.47.12.205:3306/mysql?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false";
//注意:useSSL=true / false
Connection con = null;
try
{
Class.forName(driver);
}
catch(java.lang.ClassNotFoundException e)
{
System.out.println("Connect Successfull.");
System.out.println("Cant't load Driver");
}
try
{
con=DriverManager.getConnection(URL,"root","jetflow123");
System.out.println("Connect Successfull.");
}
catch(Exception e)
{
System.out.println("Connect fail:" + e.getMessage());
}
}
}