时间:2021-07-01 10:21:17 帮助过:22人阅读
下载后别忘了解压。
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; } }
本文出自 “爬过山见过海” 博客,请务必保留此出处http://670176656.blog.51cto.com/4500575/1694961
Java后台通过JDBC连接数据库
标签:jdbc驱动包 java后台 数据库