Java JDBC连接数据库

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() ;
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值