mysql获取autoincrement,MYSQL:SQL查询以获取autoincrement字段的值

I have a table. The primary key is id and its auto incremented.

Now when I insert a new record, I need to get the id with which the record was updated.

How can I do that? If i use the query...

select max(id) from table_name

...after executing I can get the id. But can I be sure that its the id of the record that was just inserted? Because many people will be using the app at same time.

I am using php and mysql.

Can ayone provie me a sample code snippet in php with mysql?

解决方案

If you want to find out what the newest ID from an auto increment column is, you just have to run the mysql_insert_id() function right after your insert query.

Like so:

//--connection already made to database

//--now run your INSERT query on the table

mysql_query("INSERT INTO table_name (foo_column) VALUES ('everlong')");

//-- right after that previous query, you run this

$newest_id = mysql_insert_id();

And now $newest_id will contain the ID of the latest row inserted.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这段代码是一个用于创建 SQLite 数据库的帮助类,其中包含两个方法: 1. `onCreate()` 方法:在数据库首次创建时调用,用于创建数据库表和初始化数据。 2. `onUpgrade()` 方法:在数据库需要升级时调用,用于更新数据库表结构和数据。 具体来说,这段代码会创建一个名为 "loginss" 的表,该表包含三个字段:id、usname 和 uspwd。其中,id 是主键,自增长;usname 和 uspwd 分别用于存储用户的用户名和密码。 如果需要使用该类创建数据库,可按照以下步骤进行: 1. 在需要使用数据库的 Activity 中创建 Mysql1 对象,例如: ```java Mysql1 mysql1 = new Mysql1(this, "login.db", null, 1); ``` 其中,第一个参数为当前 Activity 的上下文对象;第二个参数为数据库名称;第三个参数为游标工厂对象,一般传入 null 即可;第四个参数为数据库版本号,用于管理数据库的升级和降级。 2. 调用 getWritableDatabase() 方法获取可写数据库对象,例如: ```java SQLiteDatabase db1 = mysql1.getWritableDatabase(); ``` 注意,如果数据库不存在,则会自动调用 `onCreate()` 方法创建数据库和表;如果数据库已存在,但版本号不一致,则会自动调用 `onUpgrade()` 方法更新数据库表结构和数据。 3. 使用 execSQL() 方法执行 SQL 语句来对数据库进行增、删、改、查等操作,例如: ```java String sql = "insert into loginss(usname, uspwd) values('admin', '123456')"; db1.execSQL(sql); ``` 该代码将向 loginss 表中插入一条用户名为 "admin"、密码为 "123456" 的记录。 当然,为了保证数据安全和代码健壮性,建议在实际使用中使用参数化语句或者 ContentValue 对象来进行数据库操作,而不是直接拼接 SQL 语句。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值