当前位置:Gxlcms > 数据库问题 > Java如何连接SQLServer,并实现查询、修改、删除方法

Java如何连接SQLServer,并实现查询、修改、删除方法

时间:2021-07-01 10:21:17 帮助过:5人阅读

class Const { public static final String DB_URL = "XXXX"; public static final String DB_DatabaseName = "XXX"; public static final String DB_UserName = "XXX"; public static final String DB_Password = "XXX"; }

 

2.DBHelper 方法

 1 package com.pensee.utils;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.ResultSet;
 6 import java.sql.SQLException;
 7 import java.sql.Statement;
 8 import com.pensee.config.Const;
 9 
10 public class DBHelper {
11     static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
12     static String url = "jdbc:sqlserver://"+ Const.DB_URL +";DatabaseName="+ Const.DB_DatabaseName +"";
13     static Connection con = null;
14     static Statement st = null;
15     static ResultSet res = null;
16     
17 
18     public static void dataBase() {
19         try {
20             Class.forName(driver);
21             con = DriverManager.getConnection(url, ""+ Const.DB_UserName +"", ""+ Const.DB_Password +"");
22         } catch (ClassNotFoundException e) {
23             System.err.println("装载 JDBC/ODBC 驱动程序失败。");
24             e.printStackTrace();
25         } catch (SQLException e) {
26             System.err.println("无法连接数据库");
27             e.printStackTrace();
28         }
29     }
30     
31     /**
32      * 查询SQL方法
33      * @param sql
34      * @return
35      * @throws SQLException
36      */
37     public static ResultSet find(String sql) throws SQLException{//对数据库进行数据查询
38         //获得连接
39         dataBase();
40         st=con.createStatement();
41         try {
42             res=st.executeQuery(sql);
43             return res;
44         } catch (SQLException e) {
45             e.printStackTrace();
46             return null;
47         }
48         
49     }
50     /**
51      * SQL删除修改
52      * @param sql
53      * @return
54      * @throws SQLException
55      */
56     public static boolean update(String sql) throws SQLException{//对增删改
57         //获得连接
58         dataBase();
59         st = con.createStatement();
60         try {
61             st.executeUpdate(sql);
62             return true;
63         } catch (SQLException e) {
64             e.printStackTrace();
65             return false;
66         }
67     }
68 
69 }


3. 如何调用DB

String sql = "update hr_staff_policy set HolidayPolicy = 3  where staffno =‘0092‘";
boolean result = DBHelper.update(sql);
Assert.isTrue(result);
System.out.println("SQL执行结果为:" +DBHelper.update(sql));

 

4. 效果图:

技术分享图片

Java如何连接SQLServer,并实现查询、修改、删除方法

标签:bsp   驱动   结果   class   try   for   system   jdbc   校验   

人气教程排行