package insert; import java.sql.DriverManager; import java.sql.SQLException; import com.mysql.jdbc.Connection; public class DButil { /* * 打开数据库 */ private static String driver;//连接数据库的驱动 private static String url; private static String username; private static String password; static { driver="com.mysql.jdbc.Driver";//需要的数据库驱动 url="jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8&useSSL=false";//数据库名路径 username="root"; password="xxxx"; } public static Connection open() { try { Class.forName(driver); return (Connection) DriverManager.getConnection(url,username, password); } catch (Exception e) { System.out.println("数据库连接失败!"); // TODO Auto-generated catch block e.printStackTrace(); }//加载驱动 return null; } /* * 关闭数据库 */ public static void close(Connection conn) { if(conn!=null) { try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
需要引入 mysql-connector-java-5.1.45-bin.jar
执行类
package insert; import java.sql.SQLException; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; public class jdbcconnection { public static void main(String[] args) { // TODO Auto-generated method stub insert("yangxu",1,"beijing","15022009896",false); } static void insert(String name,int age,String address,String phone,boolean flag) { String sql="insert into student(name,age,address,phone,flag) value(?,?,?,?,?)"; Connection conn=DButil.open(); try { PreparedStatement pstmt=(PreparedStatement) conn.prepareStatement(sql); pstmt.setString(1,name); pstmt.setInt(2,age); pstmt.setString(3,address); pstmt.setString(4,phone); pstmt.setBoolean(5, flag); pstmt.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { DButil.close(conn); } } }
//实体类
package insert; public class Customer { String name; int age; String address; String phone; boolean flag; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } @Override public String toString() { return "Customer [name=" + name + ", age=" + age + ", address=" + address + ", phone=" + phone + ", flag=" + flag + "]"; } }