最近,我一直在研究如何使用参数将c#中的数据存储到xampp数据库。我只需要澄清一些话题。
using System.Data;
using MySql.Data.MySqlClient;
ConnectionClass cc = new ConnectionClass();
private MySqlConnection myConn = new MySqlConnection(ConnectionClass.GetConnection());
private MySqlCommand cmDB;
cc.SetCMD("UPDATE mia_payroll.tbl_attendance SET TimeIn = @TimeIn, Date = @Date, EID = @EID;");
using(myConn) ** // 1) can I do it like this or instantiate another new MysqlConnection?**
{
cmDB = new MySqlCommand(cc.GetCMD(), myConn);
try
{
myConn.Open();
myReader = cmDB.ExecuteReader();
// 2)In MSDN it's SqlDataAdapter is mine okay?
cmDB.Parameters.Add("@EID", Text, 11);
// 3) is the position of this line correct or do I need to adjust this?
// 4) the text in () generates error how do I do this?
cmDB.Parameters["@EID"].Value = lblEID.Text;
// 5) How do I instantiate another 5 variables? (an int, a text, a time, date and a varchar)
// 6) and does parameters allow special characters into database? or should I just use regex?
while (myReader.Read())
{
TimeSpan TIN = myReader.GetTimeSpan("TimeIn");
lblTIN.Text = TIN.ToString(@"hh\:mm\:ss");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}所以学校帮不了我们太多,因为他们只教了我们C#的基础知识,而我一直在看youtube上的编程知识,他对参数没有任何了解。
发布于 2017-02-04 21:27:24
请尝试此示例,请根据您的需要进行相应的编辑。
using System.Data;
using MySql.Data.MySqlClient;
var timeIn = blabla;
var eID = lblEID.Text;
//var blablabla = blablabla;
var query = @"UPDATE mia_payroll.tbl_attendance SET TimeIn = @TimeIn, Date = @Date, EID = @EID"; //are you missing a WHERE clause? otherwise you will update all row. maybe you want to do something like below.
//var query = @"UPDATE mia_payroll.tbl_attendance SET TimeIn = @TimeIn, Date = @Date, EID = @EID WHERE rowID = @rowID";
using(MySqlConnection myConn = new MySqlConnection(ConnectionClass.GetConnection()))
using(MySqlCommand cmDB = new MySqlCommand(query, myConn))
{
try
{
//for your question to me about adding parameters value, just keep adding.
cmDB.Parameters.AddWithValue("@TimeIn", timeIn);
cmDB.Parameters.AddWithValue("@eID", eID);
//cmDb.Parameters....... and so on
//now execute query
myConn.Open();
using(MySqlDataReader myReader = cmDB.ExecuteReader())
{
while(myReader.Read())
{
//do what you want with your result.
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
myConn.Close();
}
}https://stackoverflow.com/questions/42036195
复制相似问题