JAVA连接数据库
package car.sql; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Vector; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; public class Connect { private final static String url = "jdbc:sqlserver://localhost:1433;databaseName=S_CarDB";// 数据库连接地址 private final static String user = "sa"; // 超级管理员 private final static String password = "123456"; // 密码 private static Connection conn = null;// SQL Connection private static Statement stmt; //数据库连接 public Connect() { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");// 加载驱动 } catch (Exception e1) { e1.printStackTrace(); } try { conn = DriverManager.getConnection(url, user, password);// 连接数据库 //System.out.println("数据库连接成功"); } catch (Exception e2) { e2.printStackTrace(); //System.out.println("数据库连接失败"); } } }
添加不同的方法调用数据库
public boolean compare(String num, String psd) {//判断账号密码是否正确 boolean flag = false; String sql = "select Apassword from S_Admin where Anumber='"+num+"'"; try { stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { String p = rs.getString(1); if (p.equals(psd)) { flag = true; } // rs.close(); // conn.close(); // stmt.close(); } } catch (SQLException e) { e.printStackTrace(); } return flag; } public DefaultTableModel searchChargeStandard(String ctype)//查询收费标准 { String sql = "SELECT Ctype , Cfee from S_Charge where Ctype like '%" + ctype + "%'"; // 设置dataModel的表头 DefaultTableModel dataModel = null; Vector<String> columns = new Vector<String>(); columns.add("Ctype"); columns.add("Cfee"); dataModel = new DefaultTableModel(columns, 0); try { stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { String c = rs.getString("Ctype"); String f = rs.getString("Cfee"); // 设置dataModel的数据 Vector<Object> row = new Vector<Object>(); row.add(c); row.add(f); dataModel.addRow(row); } // rs.close(); // conn.close(); // stmt.close(); } catch (SQLException e) { e.printStackTrace(); } return dataModel; }