Connect to the database through JDBC in the Java background
Connect to the local computer's SQL Server database first copy the package required to connect to jdbc to the WebContent/WEB-INF/lib directory driver package in this article there is a connection download. PS: because the driver package cannot be uploaded directly, it is packaged and uploaded again. Do not forget to decompress the package after downloading it.
Package com. exam. db;/** 1. configure the data source * 2. connect to the data source in the program **/import java. SQL. *; public class DBHelper {String driverName = "com. microsoft. sqlserver. jdbc. SQLServerDriver "; // load JDBC driver String dbURL =" jdbc: sqlserver: // localhost; DatabaseName = scan exercise "; // connect to the server and database test String userName =" sa "; // default username String userPwd = "123"; // password Connection dbConn; public DBHelper () {} public Connection connect () {try {Class. forNam E (driverName); dbConn = DriverManager. getConnection (dbURL, userName, userPwd); System. out. println ("Connection Successful! "); // If the Connection is Successful, the console outputs 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 rs1_stmt.exe cuteQuery (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 ();}}
Use in other classes
Private Connection dbConn; private Statement stat; public ScanDao () {dbConn = new DBHelper (). connect ();}/*** insert scan data * @ 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.exe cuteUpdate (SQL); return n;} catch (SQLException e) {e. printStackTrace ();} return 0 ;}