使用c#进行MySQL数据库连接 [英] MySQL database connectivity using c#
本文介绍了使用c#进行MySQL数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨..
我用c#连接到mysql。我想获得最后一次插入的id。我想在下次运行应用程序时使用最后插入的id + 1 ..
但每当我运行我的应用程序时,每次都得到id ...
谢谢..
Hi..
I m Connecting to mysql using c#.I want to get last inserted id.I want to use that last inserted id+1 when next time i will run application..
But whenever i will run my application get id 1 everytime..
Thanks..
推荐答案
这是当ID为自动递增时,从数据库表中获取最后一个插入的id。
This is to get the last inserted id from the database table when the ID is Auto-increment.
string InsertedId = "";
RowAffected = cmd.ExecuteCommand();
//After inserting the record you call this function to get the last inserted id from the table.
string query="SELECT LAST_INSERT_ID() FROM studinfo";
if (RowAffected > 0)
cmd= new MySqlCommand(query, Con);
InsertedId = cmd.ExecuteScalar();
这是另一种从表中获取lastinserted的方法。
This is another way to get the lastinserted from the table.
string filename = txtImage.Text;
byte[] imagedata;
fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
br = new BinaryReader(fs);
imagedata = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
string query = "SELECT max(ID) FROM studinfo";
cmd = new MySqlCommand(query, con);
InsertedId = cmd.ExecuteScalar();
//When the first time executes InsertedId will be null or empty since there wont be any records stored in the table
if (InsertedId == "")
{
//Assign default value as 1.
//then pass it as parameters
InsertedId = 1;
}
else
{
//it will return the last inserted id you make it plus 1 so that it will get increment to get a new id.
//then pass it as parameters
InsertedId = InsertedId + 1;
}
string cmdText = "Insert into studinfo values(@ID,@First,@Last,@address,@Image)";
cmd = new MySqlCommand(cmdText, con);
cmd.Parameters.AddWithValue("@ID", Convert.ToInt32(InsertedId));
cmd.Parameters.AddWithValue("@First", txtFirstName.Text);
cmd.Parameters.AddWithValue("@Last", txtLastName.Text);
cmd.Parameters.AddWithValue("@address", txtAddress.Text);
cmd.Parameters.AddWithValue("@Image", imagedata);
int rowaffected = cmd.ExecuteNonQuery();
//string query = "SELECT LAST_INSERT_ID() FROM studinfo";
if (rowaffected > 0)
{
MessageBox.Show("Inserted sucessfully");
Clear();
txtFirstName.Focus();
}
希望这会对你有所帮助。
Hope this helps you.
这篇关于使用c#进行MySQL数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文