java連接sql server數(shù)據(jù)庫代碼

字號:


    //鏈接數(shù)據(jù)庫代碼
    import java.sql.*;
    public class Connect
    {
    static Connection conn;
    static Statement sql;
    static ResultSet res;
    static String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
    static String dbURL="jdbc:sqlserver://127.0.0.1:1433;integratedSecurity=true;"
    dbURL=dbURL+"DatabaseName=(這里是你要連接的數(shù)據(jù)庫名稱)";
    public static Connection getConnect()
    {
    try{
    Class.forName(driverName);
    conn=DriverManager.getConnection(dbURL);
    System.out.println("SQLSERVER2008 Connection Success!");
    }catch(Exception e)
    {
    e.printStackTrace();
    }
    return conn;
    }
    //執(zhí)行增、刪、改語句
    public static int ExeSqlOper(String strSql) //方法在其它函數(shù)中直接調(diào)用就行了
    {
    int intReturn=0;
    try{
    conn=getConnect();
    sql=conn.createStatement();
    intReturn=sql.executeUpdate(strSql);
    conn.close();
    }catch(Exception e)
    {
    System.out.println(e.toString());
    }
    return intReturn;
    }
    //執(zhí)行Select語句
    public static ResultSet ExeSqlQuery(String strSql) //同樣直接調(diào)用使用
    {
    try{
    conn=getConnect();
    sql=conn.createStatement();
    res=sql.executeQuery(strSql);
    }catch(Exception e)
    {
    System.out.println(e.toString());
    }
    return res;
    }
    //主函數(shù)
    public static void main(String arges[])
    {
    getConnect();
    }
    }