jdbc對mysql進行增刪改查操作(Statement)
阿新 • • 發佈:2019-01-29
創立資料庫school
創立表格students
create table students(
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
sex VARCHAR(4) NOT NULL,
age INT(4) NOT NULL,
PRIMARY KEY ( id )
);
下面是增刪改查的完整程式碼
package java_mysql; import java.sql.*; public class main{ // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://127.0.0.1/school"; // Database credentials static final String USER = "root"; static final String PASS = "appleyuchi"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); //STEP 4: Execute a query //---------------------------下面是增操作----------------------------------------------------------- stmt = conn.createStatement(); // // String sql = "INSERT INTO students (name,sex,age)" + // "VALUES ('Ender','male',8)"; // stmt.executeUpdate(sql); // sql = "INSERT INTO students (name,sex,age)" + // "VALUES ('Bean','male',7)"; // stmt.executeUpdate(sql); // sql = "INSERT INTO students (name,sex,age)" + // "VALUES ('Petra', 'Fema',9)"; // stmt.executeUpdate(sql); // sql = "INSERT INTO students (name,sex,age)" + // "VALUES('God','fema',232)"; // stmt.executeUpdate(sql); // System.out.println("Inserted records into the table..."); //---------------------------下面是刪操作------------------------------------------- // String name="Petra"; // String sql = "delete from students where Name='" + name + "'"; // stmt.executeUpdate(sql); //---------------------------下面是改操作------------------------------------------- // int age=78; // String name="God"; // String sql = "update students set Age='" + age + "' where Name='" + name + "'"; // stmt.executeUpdate(sql); //---------------------------下面是查操作------------------------------------------- int age=8; String sql="select * from students where age='"+age+"'"; ResultSet rs=stmt.executeQuery(sql);//執行查詢該表 while(rs.next()) { int id=rs.getInt(1); String name=rs.getString(2); String sex=rs.getString(3); System.out.println(id+","+name+","+sex); } }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) conn.close(); }catch(SQLException se){ }// do nothing try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end JDBCExample