完成数据库的连接
获取连接参数
拷贝1.数据库URL 2.驱动程序类 3.用户
编写Servlet
1.创建连接对象
1 Connection con = null; 2 PreparedStatement prst = null; 3 ResultSet rs = null;
2.写入连接参数
1 String url = "数据库URL"; 2 String driver = "驱动程序类"; 3 String user = "用户"; 4 String password = "数据库用户密码";
3.连接数据库,编写sql语句
1 Class.forName(driver) 2 con = DriverManager.getConnection(url,user,password); 3 String sql = "UPDATE [表] SET [目标列]=? WHERE [目标列]=?";
4.读取execel
1 Workbook book = Workbook.getWorkbook(new File("文件路径")); 2 Sheet sheet = book.getSheet(工作表序号);
5.写一个for循环
1 //一个整型,注意excel从第几行开始是更新值,注意范围设置,i++ 2 for (int i = 1; i < 215; i++) { 3 // 使用jxl包,读取单元格(列序号,行序号) 4 jxl.Cell cell0 = sheet.getCell(0, i); 5 jxl.Cell cell1 = sheet.getCell(1, i); 6 //声明变量,取单元格的文本内容 7 String result0 = cell0.getContents(); 8 String result1 = cell1.getContents(); 9 //编译预编译语句,将两个单元格内容传入sql语句 10 prst = con.prepareStatement(sql); 11 // 注意位置(数字表示第几个问号,传入变量) 12 prst.setString(2, result0); 13 prst.setString(1, result1); 14 //执行sql语句 15 prst.executeUpdate(); 16 }
6.关掉excel读取
1 book.close();
完整代码
1 protected void processRequest(HttpServletRequest request, HttpServletResponse response) 2 throws ServletException, IOException { 3 response.setContentType("text/html;charset=UTF-8"); 4 PrintWriter out = response.getWriter(); 5 Connection con = null; 6 PreparedStatement prst = null; 7 ResultSet rs = null; 8 String url = "jdbc:sqlserver://localhost:***;databaseName=***"; 9 String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; 10 String user = "sa"; 11 String password = "***"; 12 try { 13 Class.forName(driver); 14 con = DriverManager.getConnection(url, user, password); 15 String sql = "UPDATE [***] SET [***]=? WHERE [***]=? "; 16 Workbook book = Workbook.getWorkbook(new File("****")); 17 Sheet sheet = book.getSheet(*); 18 //一个整型,注意excel从第几行开始是更新值,注意范围设置,i++ 19 for (int i = *; i <***; i++) { 20 // 使用jxl包,读取单元格(列序号,行序号) 21 jxl.Cell cell0 = sheet.getCell(0, i); 22 jxl.Cell cell1 = sheet.getCell(1, i); 23 //声明变量,取单元格的文本内容 24 String result0 = cell0.getContents(); 25 String result1 = cell1.getContents(); 26 //编译预编译语句,将两个单元格内容传入sql语句 27 prst = con.prepareStatement(sql); 28 // 注意位置(数字表示第几个问号,传入变量) 29 prst.setString(2, result0); 30 prst.setString(1, result1); 31 //执行sql语句 32 prst.executeUpdate(); 33 } 34 out.print("<h1><strong>成功!</strong></h1>"); 35 book.close(); 36 } catch (BiffException ex) { 37 Logger.getLogger(doH.class.getName()).log(Level.SEVERE, null, ex); 38 } catch (ClassNotFoundException ex) { 39 Logger.getLogger(doH.class.getName()).log(Level.SEVERE, null, ex); 40 } catch (SQLException ex) { 41 Logger.getLogger(doH.class.getName()).log(Level.SEVERE, null, ex); 42 } 43 }
注意事项:
1.该方法用的jxl的包,需要在库中导入
2.操作数据库需要try{}catch 来抛出异常,先码
Class.forName(driver);
处理方式
接着码
prst = conn.prepareStatement(sql);
添加catch子句