1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.sql.PreparedStatement; public class javatest1{ public static void main(String[] args)throws Exception{ Class.forName("com.mysql.cj.jdbc.Driver"); Connection connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mysql","root","john376577"); Statement statement=connection.createStatement(); String sql="CREATE TABLE `user1` (`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(45) DEFAULT NULL,`phone` varchar(45) DEFAULT NULL,`age` int(8) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8"; statement.executeUpdate(sql); statement.close(); String sql="insert into user (`name`,`phone`,`age`)values(?,?,?,)"; PreparedStatement statement=connection.prepareStatement(sql); statement.setString(1,"Peter"); statement.setString(2,"13888888888"); statement.setString(3,22); System.out.println("要插入的数据为:"+statement.toString()); statement.executeUpdate(); statement.close(); String sql="insert into user (`name`,`phone`,`age`)values(?,?,?,)"; PreparedStatement statement=connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS); statement.setString(1,"Peter"); ...; statement.executeUpdate(); ResultSet generatedIds=statement.getGeneratedKeys(); while(generatedIds.next()) System.out.println(generatedIds.getLong(1)); statement.close(); Statement queryStatement=connection.createStatement(); ResultSet resultSet=queryStatement.executeQuery("select * from user"); while(resultSet.next()) System.out.println(resultSet.getString("id")+resultSet.getString("name")+resultSet.getString("age")); connection.setAutoCommit(false); Statement statement=connection.createStatement(); statement.addBatch("..."); statement.addBatch("..."); statement.executeBatch(); connection.commit(); connection.rollback(); connection.close(); }; };
|