Mysql的两个问题

xiaoxiao2025-12-30  7

第一题:一张表,里面有ID自增主键,当insert了17条记录之后,删除了第15,16,17条记录,再把Mysql重启,再insert一条记录,这条记录的ID是18还是15 第二题:还是MYSQL的,一张表有还是有ID自增主键,用JDBC insert一条语句之内,怎么在JAVA程序里面获得这条记录的ID. 第一题:这个要看Mysql表的类型 我现在知道的有两种,一种是MyISAM,另一种是InnoDB MYSQL默认的就是InnoDB InnoDB是把表的主键最大值放到内存里面,所以MYSQL重启之后就会丢失(在WINDOW下,这是MYSQL默认的) MyISAM是把表的主键最大值放到文件里面,所以MYSQL重启之后不会丢失 可以在创建表的时候显示指定 create table t_test(id int not null auto_increment primary key,name varchar(255)) ENGINE=InnoDB; 或create table t_test(id int not null auto_increment primary key,name varchar(255)) ENGINE=MyISAM; 还可以通过 SHOW TABLE STATUS;命令可以看到表的类型 使用ALTER命令可以对单个表的类型进行修改 ALTER TABLE talbe_name ENGINE=InnoDB; 用 SHOW GLOBAL VARIABLES LIKE '%engine%'; 可以看到MySQL当前默认的新生成表的类型。 第二题: 有两种方法, 1.JDBC有这个API,Statement.getGeneratedKeys(); Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection ("jdbc:mysql://localhost:3306/testid","root","root"); // 创建带问号的参数化语句 String template = "insert into t_test(name) values(?) "; PreparedStatement statement = connection.prepareStatement (template); statement.setString(1, "langhua1"); statement.execute(); ResultSet rs = statement.getGeneratedKeys(); while(rs.next()){//获得主键 System.out.println(rs.getInt(1)); } statement.close(); rs.close(); connection.close();connection.setAutoCommit(false);Statement stat = connection.getStatement();stat.executeUpdate("insert into test (name,password) values('123','321')");ResultSet rs = stat.executeQuery("select id from test where name='123'");rs.next();System.out.println(rs.getInt('id'));connection.commit(); 2.可以利用MySQL语句获得,但这个就不是通用语句了:SELECT LAST_INSERT_ID();
转载请注明原文地址: https://www.6miu.com/read-5041749.html

最新回复(0)