Java连接数据库示例

来源:互联网 发布:怎么创建数据透视表 编辑:程序博客网 时间:2024/04/28 14:58
package TestDB;

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

public class testMySQL {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Connection ct = null;
        Statement stmt = null;
        ResultSet rs = null;
        PreparedStatement pstmt = null;
        try {
            
//            //Oracle连接
//            Class.forName("oracle.jdbc.driver.OracleDriver");
//            ct = DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.2:1521:AAA","root","root");

//            //SQLServer连接
//            Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
//            ct = DriverManager.getConnection(
//                    "jdbc:microsoft:sqlserver://localhost:1433;databaseName=AAA", "root", "root");

            //MySQL连接
            Class.forName("com.mysql.jdbc.Driver");
            ct = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/aaa", "root", null);
            stmt = ct.createStatement();
            //执行单条更新
            stmt.executeUpdate("insert into t_user(username, password) values('测试','密码')");
            //执行批处理更新
            stmt.addBatch("insert into t_user(username, password) values('测试1','密码1')");
            stmt.addBatch("insert into t_user(username, password) values('测试2','密码2')");
            stmt.executeBatch();
            //查询数据
            rs = stmt.executeQuery("select * from t_user");
            while(rs.next()){
                System.out.println(rs.getString("username"));
            }
            //带参数的SQL
            pstmt = ct.prepareStatement("update t_user set password = ? where username = ?");  
            pstmt.setString(1, "111");
            pstmt.setString(2, "测试");
            pstmt.executeUpdate();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try{
                if(rs!= null){
                    rs.close();
                    rs=null;
                }
            }catch(Exception e){}
            try{
                if(stmt!= null){
                    stmt.close();
                    stmt=null;
                }
            }catch(Exception e){}
            try{
                if(pstmt!= null){
                    pstmt.close();
                    pstmt=null;
                }
            }catch(Exception e){}
            try{
                if(ct != null){
                   ct.close();
                   ct = null;
                }
            }catch(Exception ex){
                ex.printStackTrace();
            }
        }
    }
}