mysql 数据库连接

1、需要mysql驱动包:mysql-connector-java-5.1.7-bin.jar

2、  

package com.jmu.ccjoin.web.controller;

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

import com.mysql.jdbc.Driver;


public class Test {

    public static void main(String[] args) {
        String url = "jdbc:mysql://172.16.1.23:3306/jmuv3";
        String username = "root";
        String password = "123.com";
        Statement stmt = null;
        Connection connect = null;
        try {
            // 注册驱动有多种方法
            // 方法一:
             Class.forName("com.mysql.jdbc.Driver");
             connect = DriverManager.getConnection(url,username,password);

            // 方法二:
            // Driver driver = new com.mysql.jdbc.Driver();
            // DriverManager.registerDriver(driver);
            // Connection connect = DriverManager.getConnection(url,username,password);
           
            //方法三:
            //Driver driver = new com.mysql.jdbc.Driver();
            //Properties props = new Properties();
            //props.setProperty("user", username);//key是固定的user和password
            //props.setProperty("password", password);
            //Connection connect = driver.connect(url, props);

            System.out.println("已经连接数据库");
       // connect.setAutoCommit(false);//启用手动事务支持 stmt
= connect.createStatement(); ResultSet rs = stmt.executeQuery("select * from users limit 10");
       // connect.commit();//启用手动事务支持
while (rs.next()) { System.out.println(rs.getString("username")); } // 完成后关闭 rs.close(); stmt.close(); connect.close(); } catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if (connect != null) {
                    connect.close();
                    // connect.rollback();//启用手动事务支持
                } }
catch(SQLException se){ se.printStackTrace(); } } System.out.println("Goodbye!"); } }

 



 

posted @ 2018-05-23 17:59  乌瑟尔  阅读(142)  评论(0编辑  收藏  举报