java连接数据库SQLServer和MySql

import java.sql.*;
/*
 * 首先需要把相应的(.jre)加载到工程中 ;(可以在网上下载--mysql java jar或者 mssql java jar)
 * 一:在工程下新建一个文件夹,将相应的驱动移进去;
 * 二: 配置     JRE System Library --Build path--Configure Build path 
 *    选择 Add JREs 然后选择刚才新建文件夹相应的驱动添加!
*/
public class SQLConnect {
	Connection con;//  连接
	Statement stat;//  新建查询
	ResultSet rs;//   结果集  
	public SQLConnect(String drive,String url,String name,String password) throws SQLException {
		try {
			Class.forName(drive);
			con=DriverManager.getConnection(url, name, password);
			stat=con.createStatement();
			 System.out.println("连接成功!");
		} catch (ClassNotFoundException e) {
		  System.err.println("连接失败!!");
			e.printStackTrace();
		}
	}
	public static void main(String[] args) throws SQLException {
		//Mysql连接 
		String driver="com.mysql.jdbc.Driver"; //驱动
		String url="jdbc:mysql://localhost:3306/Information";//Information 为数据库名   mysql的端口号一般为3306;
		String name="root";  //登录用户名
		String password="0.0.123++--.";  //密码
		//sqlserver连接
		/*String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
		String url="jdbc:sqlserver://localhost:1433;DatabaseName=Flight;"; // Flight 为数据库名 sqlsever 端口一般为1433
		String name="sa";  
		String password="123456";*/
	    SQLConnect sqlc=new SQLConnect(driver, url, name, password);
	
	}  
}

猜你喜欢

转载自blog.csdn.net/momo_f/article/details/80517927