Java JDBC連線資料庫 UPDATE更新
阿新 • • 發佈:2019-01-03
package com.edu; import java.sql.*;//匯入包 public class TestUpdate { public static void main(String[] args) { try { //載入並註冊驅動程式 Class.forName("com.mysql.jdbc.Driver"); //定義連線字串 String url="jdbc:mysql:///test"; //連線資料庫 Connection conn=DriverManager.getConnection(url, "root", "root"); //sql語句 String sql="update users set name=?,sex=?,age=?,addr=? where name=?"; //預置物件 PreparedStatement pstmt=conn.prepareStatement(sql); //設定佔位符值 pstmt.setString(1, "張三"); pstmt.setString(2, "男"); pstmt.setInt(3, 20); pstmt.setString(4, "成都市新都區"); pstmt.setString(5, "lili"); //執行sql語句,返回影響行數 int res=pstmt.executeUpdate(); if(res>0){ System.out.println("更新資料成功"); } pstmt.close(); conn.close(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }