- 温馨提示:在使用这程序之前,需要向项目中导入相应数据库的驱动并创建数据库
- 第一种连接MySQL
- importjava.sql.Connection;
- importjava.sql.DriverManager;
- /**
- * 连接 MySQL数据库
- * 下载驱动网址:”http://www.mysql.org”
- */
- public classDemo2_GetConn {
- public Connection conn = null; // 创建Connection对象
- public ConnectiongetConnection() { // 获取数据库连接方法
- try {
- //Class.forName(com.mysql.jdbc.Driver); // 加载数据库驱动
- DriverManager.registerDriver(newcom.mysql.jdbc.Driver());
- //指定连接数据的URL
- String url = "jdbc:mysql://localhost:3306/day08";
- String user = "root"; //指定连接数据库的用户名
- String password = "root"; //指定连接数据库的密码
- conn =DriverManager.getConnection(url, user, password);
- if (conn != null) { // 如果Connection实例不为空
- System.out.println("数据库连接成功"); //提示信息
- }
- } catch(Exception e) {
- e.printStackTrace();
- }//异常处理
- return conn;//返回Connection
- }
- /**
- * @param args
- */
- public static voidmain(String[] args) {//主方法
- Demo2_GetConn getConn = newDemo2_GetConn(); // 创建Demo2_GetConn对象
- getConn.getConnection(); // 调用连接数据库方法
- }
- }
- 第二种连接SQL Server
- importjava.sql.Connection;
- importjava.sql.DriverManager;
- /**
- * 连接SQL Server2005数据库连接SQL
- * Server2005数据库应用的驱动程序为"sqljdbc.jar",可以到Microsoft的官方网站上下载地址:
- * "http://www.microsoft.com"
- *
- */
- public classDemo3_Server {
- public Connection conn = null; // 创建Connection对象
- // 获取数据库连接方法
- public ConnectiongetConnection() {
- // 加载数据库驱动
- try {
- Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDrive");
- // 指定连接数据库的URL
- String url = "jdbc:sqlserver://localhost:1433;databaseName=db_database19";
- String user = "sa"; // 指定连接数据库的用户
- String passWord = ""; // 指定连接数据库的密码
- conn =DriverManager.getConnection(url, user, passWord);
- // 如果Connection实例不为空
- if (conn != null) {
- System.out.println("数据库连接成功"); // 提示信息
- }
- } catch(Exception e) {
- e.printStackTrace();
- }
- return conn; // r返回Connection对象
- }
- /**
- * @param args
- */
- public static voidmain(String[] args) {
- Demo3_Server getConn = newDemo3_Server();// 创建getConn对象
- getConn.getConnection(); // 调用连接数据库方法
- }
- }
- //第三连接
- importjava.sql.Connection;
- importjava.sql.DriverManager;
- /**
- * 连接Oracle11g数据库应用的程序这"ojdbc6.jar",可以在Oracle安
- * 装后的文件夹中找到,路径是"\product\11.2.0\dbhome_1\jdbc\lib"
- *
- */
- public classDemo3_Oracle {
- public Connection conn = null; //创建Connection
- public ConnectiongetConnection(){ //获取连接方法
- try {
- Class.forName("oracle.jdbc.driver.OracleDriver");
- String url = "jdbc:oracle:thin:@localhost:1521:orcl"; //指定连接数据库的URL
- String user = "system"; //数据库用户名
- String passWord = "justice";//指定连接数据库的密码
- conn =DriverManager.getConnection(url, user, passWord);
- if(conn != null){
- System.out.println("连接成功");
- }
- } catch(Exception e) {
- e.printStackTrace();
- } //加载数据库驱动
- return conn; //返回Connection对象
- }
- /**
- * @param args
- */
- public static voidmain(String[] args) {
- Demo3_Oracle getConn = newDemo3_Oracle();
- getConn.getConnection(); //调用连接数据库方法
- }
- }