1. 連接數據庫,得到數據庫連接變量
注意連接數據庫的時候
(1)打開DB Browser 新建一個Database Driver,注意添加Driver JARs的時候添加的包,我的是mysql-connector-java-5.0.3-bin.jar
(2)要將數據庫jar包拷貝到工程下的WEB-INF\lib下
import java.sql.Connection;//java包 public class DBConnection { private String dbDriver="com.mysql.jdbc.Driver"; private String dbUrl="jdbc:mysql://[ip地址]:[端口號]/[數據庫名]";//根據實際情況變化 private String dbUser="root"; private String dbPass="root"; public Connection getConn() { Connection conn=null; try { Class.forName(dbDriver); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { conn = DriverManager.getConnection(dbUrl,dbUser,dbPass);//注意是三個參數 } catch (SQLException e) { e.printStackTrace(); } return conn; } }
public int insert() { int i=0; String sql="insert into (表名)(列名1,列明2) values(?,?)"; Connection cnn=getConn(); try{ PreparedStatement preStmt =cnn.prepareStement(sql); preStmt.setString(1,值); preStmt.setString(2,值);//或者:preStmt.setInt(1,值); i=preStmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } return i;//返回影響的行數,1為執行成功 }
public int update { int i=0; String sql="update (表名) set (列名1)=?,列明2=? where (列名)=?";//注意要有where條件 Connection cnn=getConn(); try{ PreparedStatement preStmt =cnn.prepareStatement(sql); preStmt.setString(1,(值)); preStmt.setString(2,(值));//或者:preStmt.setInt(1,值); preStmt.setInt(3,(值)); i=preStmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } return i;//返回影響的行數,1為執行成功 }
public String select { String sql = "select * from (表名) where (列名)=(值)"; Connection cnn = getConn();//此處為通過自己寫的方法getConn()獲得連接 try { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); if(rs.next()) { int m1 = rs.getInt(1);//或者為rs.getString(1),根據數據庫中列的值類型確定,參數為第一列 String m2 = rs.getString(2); } //可以將查找到的值寫入類,然後返回相應的對象 } catch (SQLException e) { e.printStackTrace(); } return (相應的值的變量); }
public int delete() { String sql = "delete from (表名) where (列名)=(值)"; int i=0; Connection conn = getConn();//此處為通過自己寫的方法getConn()獲得連接 try { Statement stmt = conn.createStatement(); i = stmt.executeUpdate(sql); } catch (SQLException e) { e.printStackTrace(); } return i;//如果返回的是1,則執行成功; }