首页 > 代码库 > JDBC的连接

JDBC的连接

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

public class MyConnection {

	  Connection con;
	public static void main(String[] args) {
		MyConnection mycon=new MyConnection();
		Connection c=mycon.getConnection();

	}
	public  Connection getConnection(){
		// 驱动程序名
	    String driver = "com.mysql.jdbc.Driver";
	    // URL指向要访问的数据库名score
	    String url="jdbc:mysql://localhost:3306/score";
	    //String url="jdbc:mysql://127.0.0.1:3306/score";
	    // MySQL配置时的用户名
	    String user = "root"; 
	    // MySQL配置时的密码
	    String password = "123456";
	  
	    try {
	    	//加载驱动
			Class.forName(driver);
			
			 // 连续数据库
			con=DriverManager.getConnection(url, user, password);
			
			if(!con.isClosed())System.out.println("数据库连接成功!");
			
			//Statement用来执行sql语句
			Statement statement=con.createStatement();
			
			// 要执行的SQL语句
			String sql="select * from Student";
			
			 // 结果集
			ResultSet re=statement.executeQuery(sql);
			
			//遍历数据
			while(re.next()){
				String Sid=re.getString(1);
				String Sname=re.getString(2);
				String Sage=re.getString(3);
				String Ssex=re.getString(4);
				String Szhuanye=re.getString(5);
				
				System.out.println("Sid:"+Sid+"  Sname:"+Sname+"  Sage:"+Sage+"  Ssex:"+Ssex+"  Szhuanye:"+Szhuanye);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	    return con;
	}

}