JAVA学习随笔之JDBC的典型用法之DriverManager

作为管理一组JDBC驱动的基础的服务。

一、getConnection方法

//一个参数
public static Connection getConnection(String url) throws SQLException
//String url:数据库URL

//两个参数
public static Connection getConnection(String url,Properties info) throws SQLException
//String url:数据库URL
//Properties info:一系列字符串键值对用来作为连接参数,一般至少包括user和password两个属性。

//三个参数
public static Connection getConnection(String url, String user,String password) throws SQLException
//String url:数据库URL//String user:连接数据库的用户名//String password:连接数据库的密码

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class TestDriverManager {

	public void testConnection() throws Exception {
		Class.forName("com.mysql.jdbc.Driver");
		
		//一个参数
		// DriverManager.getConnection("com.mysql.jdbc.Driver");
		//两个参数
		Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/user_info", createPropeties());
		//三个参数
		// Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/user_info", "root", "root");

		Statement statement = connection.createStatement();
		ResultSet query = statement.executeQuery("select * from test;");
		while (query.next()) {
			System.out.println(query.getInt(1));
		}
	}
	
	/**
	 * 用于声明一个存储用户名和密码的Properties对象
	 * @return Properties
	 */
	public Properties createPropeties(){
		Properties properties = new Properties();
		properties.setProperty("user", "root");
		properties.setProperty("password", "root");
		return properties;
	}

	public static void main(String[] args) throws Exception {
		new TestDriverManager().testConnection();
		;
	}
}


你可能感兴趣的:(JAVA)