1. 程式人生 > 其它 >JDBC之連線資料庫及增刪改查

JDBC之連線資料庫及增刪改查

技術標籤:JDBC資料庫java

//Connection:資料庫連線物件
Connection connection=null;
//Statement:執行sql的物件
Statement statement=null;
//resulted 結果集,Result是結果的意思,Set是集合的意思,通過statement.execute獲取資料庫的每一條資料形成的一個Set集合
ResultSet resultSet=null;
try {
    //註冊驅動   告訴程式該使用哪一個資料庫驅動jar
    Class.forName("com.mysql.jdbc.Driver"
); //jdbc:mysql://ip地址(域名):埠號/資料庫名稱 String url = "jdbc:mysql://localhost:3306/first"; String user = "root"; String password = "970329"; //獲取連線 DriverManager:驅動管理物件 connection= DriverManager.getConnection(url,user,password); //建立Statement物件 statement =
connection.createStatement(); //插入一條語句 String sqlAdd = "INSERT INTO students (stu_name,stu_age,stu_sex,tea_id,is_del) VALUES ('王一博',25,1,1,0)"; //執行插入語句 /*方法executeUpdate 用於執行 INSERT、UPDATE 或 DELETE 語句以及 SQL DDL(資料定義語言)語句 * executeUpdate 的返回值是一個整數,指示受影響的行數(即更新計數) * */ int
add = statement.executeUpdate(sqlAdd); System.out.println("增加" + add + "條資料"); //修改一條語句 String sqlUpdate = "UPDATE students SET stu_name = '黃景瑜' WHERE stu_id = 7"; //執行修改語句 int update = statement.executeUpdate(sqlUpdate); System.out.println("修改" + update + "條資料"); //刪除一條語句 String sqlDelete = "DELETE FROM students WHERE stu_id = 10"; //執行刪除語句 int delete = statement.executeUpdate(sqlDelete); System.out.println("刪除" + delete + "條資料"); //定義SQL語句 String sql="SELECT * FROM students"; //執行SQL /*方法executeQuery 用於產生單個結果集的語句,例如 SELECT 語句。*/ resultSet = statement.executeQuery(sql); List<Students> list=new ArrayList<Students>(); while (resultSet.next()){ //通過列名獲取列的值 int student_id=resultSet.getInt("stu_id"); String student_name=resultSet.getString("stu_name"); int student_age=resultSet.getInt("stu_age"); int student_sex=resultSet.getInt("stu_sex"); int teacher_id=resultSet.getInt("tea_id"); int is_del=resultSet.getInt("is_del"); //建立物件 將獲取的資料存入物件中 Students students=new Students(); students.setStudentId(student_id); students.setStudentName(student_name); students.setStudentAge(student_age); students.setStudentSex(student_sex); students.setTeacherId(teacher_id); students.setIsDel(is_del); //將賦值完成的物件再次存入集合中 list.add(students); } for (Students s:list ) { System.out.println(s); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); }finally { try { connection.close(); statement.close(); } catch (SQLException e) { e.printStackTrace(); } }`