dbclass.java~1~

来自「自己写的一个JAVA实现的学生成绩管理系统」· JAVA~1~ 代码 · 共 79 行

JAVA~1~
79
字号
import java.sql.*;
import java.util.Iterator;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.DriverManager;

public class DBClass 
{
   String url = "jdbc:microsoft:sqlserver://127.0.0.1:1433";
   //url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs";
   private Connection sqlCon;//连接
   private Statement pstmt;//连接状态
   ResultSet rs;//结果集
   public DBClass () 
   {
      sqlCon = null;
      pstmt = null;
      rs = null;
   }
   public ResultSet executeSQL(String SQLString, String databaseString) 
   {
      try 
      {
         Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();//注册
         sqlCon = DriverManager.getConnection(url, "sa", "");
         sqlCon.setCatalog(databaseString);
         sqlCon.setAutoCommit(true);
         String sqlString = SQLString.trim();
         //pstmt = sqlCon.prepareStatement(sqlString);
         pstmt = sqlCon.createStatement();
         if(sqlString.substring(0, 1).equals("s")) 
         {
            rs = pstmt.executeQuery(sqlString);
            return rs;
         }
         else 
         {
            pstmt.executeUpdate(sqlString);
         }
      }
      catch(InstantiationException e) 
      {
         e.printStackTrace();//To change body of catch statement use Options | File Templates.
      }
      catch(IllegalAccessException e) 
      {
         e.printStackTrace();//To change body of catch statement use Options | File Templates.
      }
      catch(ClassNotFoundException e) 
      {
         e.printStackTrace();//To change body of catch statement use Options | File Templates.
      }
      catch(SQLException e) 
      {
         e.printStackTrace();//To change body of catch statement use Options | File Templates.
      }
      return null;
   }
   public void closeDatabase() throws SQLException 
   {
      if(rs != null) 
         rs.close();
      if(pstmt != null) 
         pstmt.close();
      if(sqlCon != null) 
         sqlCon.close();
   }
   public static void main(String[] args) throws Exception 
   {
      DBClass a = new DBClass();
      a.executeSQL("select * from student", "studentdatabase");
      if(a.rs.next()) 
         System.out.println(a.rs.getString("name"));
   }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?