package MysqlConnection;
import java.sql.*;
public class Test {
public static void main(String[] args) {
// https://blog.csdn.net/javaniuniu/article/details/52403509
try {
// 1、加载JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 2、提供JDBC连接的URL
String url = "jdbc:mysql://127.0.0.1/Proxy?useUnicode=true&characterEncoding=UTF-8&useSSL=false";
// 3、创建数据库的连接
String user = "user", password = "password";
Connection conn = DriverManager.getConnection(url, user, password);
// 4、创建一个Statement
// •要执行SQL语句,必须获得java.sql.Statement实例,Statement实例分为以下3 种类型:
// 1、执行静态SQL语句。通常通过Statement实例实现。
// 2、执行动态SQL语句。通常通过PreparedStatement实例实现。
// 3、执行数据库存储过程。通常通过CallableStatement实例实现。
Statement statement = conn.createStatement();
// 5、执行SQL语句
// Statement接口提供了三种执行SQL语句的方法:executeQuery、executeUpdate 和execute
ResultSet res = statement.executeQuery("select * from Spider_proxy");
// 6、处理结果
String ip, port, type;
while(res.next()) {
ip = res.getString(1);
port = res.getString(2);
type = res.getString(3);
System.out.println(type + "://" + ip + ":" + port);
}
// 7、关闭JDBC对象
if(res != null){ // 关闭记录集
res.close() ;
}
if(statement != null){ // 关闭声明 try{
statement.close() ;
}
if(conn != null){ // 关闭连接对象 try{
conn.close() ;
}
}
catch (ClassNotFoundException e) {
System.out.println("找不到驱动程序类,加载驱动失败!");
e.printStackTrace() ;
}
catch(SQLException e){
System.out.println("数据库连接失败!");
e.printStackTrace() ;
}
catch (Exception e) {
e.printStackTrace() ;
}
}
}
Java JDBC连接数据库
最新推荐文章于 2023-11-07 15:56:42 发布