使用JDBC相关方法,在数据库mybase 中创建一个数据表。
id int[主键,自动增长] username varchar(32) password varchar(32) age int sex enum('男','女')
并写入一条数据:username password age sex:andy,123,25,男
仅供参考:为了方便,我是直接把全部的方法和用到的类都定义在一个类里面:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class Test2 { //main函数 public static void main(String[] args) { Person person = new Person("andy","123","25","男"); Test2 test2 = new Test2(); test2.add(person); } //添加数据 public int add(Person person) { String sql = " INSERT INTO mydate(username,password,age,sex) VALUES (?,?,?,?)"; Object[] objects = {person.getUsername(),person.getPassword(),person.getAge(),person.getSex()}; int rows = -1; Connection conn = null; PreparedStatement ps = null; try { conn = getConnection(); ps = conn.prepareStatement(sql); if (objects != null) { for (int i = 0; i < objects.length; i++) { ps.setObject((i+1), objects[i]); } } rows = ps.executeUpdate(); }catch (SQLException e) { e.printStackTrace(); }finally { } return rows; } static { // 1.加载驱动包 try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } //获取数据库连接 public static Connection getConnection() { // 2.得到数据库连接(桥) Connection conn = null; try { conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybase", "root", "123456"); } catch (Exception e) { e.printStackTrace(); } return conn; } } //一个实体类 class Person{ private String username; private String password; private String age; private String sex; public Person() { super(); } public Person(String username, String password, String age, String sex) { super(); this.username = username; this.password = password; this.age = age; this.sex = sex; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }