萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 編程語言綜合 >> java連接sql server數據庫代碼

java連接sql server數據庫代碼

   //鏈接數據庫代碼

  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=(這裡是你要連接的數據庫名稱)";

  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;

  }

  //執行增、刪、改語句

  public static int ExeSqlOper(String strSql) //方法在其它函數中直接調用就行了

  {

  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;

  }

  //執行Select語句

  public static ResultSet ExeSqlQuery(String strSql) //同樣直接調用使用

  {

  try{

  conn=getConnect();

  sql=conn.createStatement();

  res=sql.executeQuery(strSql);

  }catch(Exception e)

  {

  System.out.println(e.toString());

  }

  return res;

  }

  //主函數

  public static void main(String arges[])

  {

  getConnect();

  }

  }

copyright © 萬盛學電腦網 all rights reserved