连接的是本地电脑的SQL Server数据库
首先把连接jdbc所需的包复制到WebContent/WEB-INF/lib目录下
驱动包在本文后面有连接下载。
PS: 因为该驱动包不能直接上传,所以打包了一份再上传。
下载后别忘了解压。
package com.exam.db; /* * 1.配置数据源 * 2.在程序中连接数据源 * */ import java.sql.*; public class DBHelper { String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; //加载JDBC驱动 String dbURL = "jdbc:sqlserver://localhost; DatabaseName=扫描练习"; //连接服务器和数据库test String userName = "sa"; //默认用户名 String userPwd = "123"; //密码 Connection dbConn; public DBHelper(){ } public Connection connect(){ try { Class.forName(driverName); dbConn = DriverManager.getConnection(dbURL, userName, userPwd); System.out.println("Connection Successful!"); //如果连接成功 控制台输出Connection Successful! } catch (Exception e) { e.printStackTrace(); } return dbConn; } public void query(){ String sql = "select * from scantable"; Statement stmt; try { stmt = dbConn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet rs=stmt.executeQuery(sql); while(rs.next()){ System.out.println(rs.getString(1)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] srg) { new DBHelper().query(); } }
在其他类中使用
private Connection dbConn; private Statement stat; public ScanDao(){ dbConn = new DBHelper().connect(); } /** * 插入扫描数据 * @param uuid * @param billcode * @param scantime * @return */ public int inserData(ScanBean bean){ String sql = "insert into scantable values(‘"+bean.getUuid()+"‘, ‘"+bean.getBillcode()+"‘, ‘"+bean.getScantime()+"‘)"; try { stat = dbConn.createStatement(); int n = stat.executeUpdate(sql); return n; } catch (SQLException e) { e.printStackTrace(); } return 0; } }
时间: 2024-10-21 16:24:41