我需要做的是基本上取用户名(已经存储为变量)和他们的分数(也是一个变量)并在他们按“提交”时将其存储在我的数据库中。这是按钮点击的代码。
private void btnSubmitScore_Click(object sender, EventArgs e)
{
string connStr = "server=server; " +
"database=databasename; " +
"uid=username; " +
"pwd=password;";
MySqlConnection myConn = new MySqlConnection(connStr);
}
显然我已经更改了login
详细信息等。我已经浏览了一下,并且只设法找到关于如何在表单中显示数据的混乱代码(我稍后会这样做),但是现在,我需要知道如何将sName
和iTotalScore
添加到数据库中。 (字段在数据库中称为'Name'
和'Score'
答案 0 :(得分:0)
我不熟悉MySql连接器,但代码应该是:
private void Insert()
{
string connStr = "server=server; " +
"database=databasename; " +
"uid=username; " +
"pwd=password;";
string query = "INSERT INTO TableName('Name','Score) VALUES (@name, @score);";
using(MySqlConnection connection = new MySqlConnection(connStr))
{
MySqlCommand insertCommand = new MySqlCommand(connection,command);
insertCommand.Paramaters.AddWithValue("@name",sName);
insertCommand.Paramaters.AddWithValue("@score",iTotalScore);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
答案 1 :(得分:0)
您将使用SqlConnection
,SqlCommand
及其属性的组合。连接本质上是你的代码的东西。该命令是文字SQL语句或对存储过程的调用。
一个常见的C#习惯用法是围绕第一行形成代码,如下所示:
using (SqlConnection myConnection = new SqlConnection()) {
string doThis = "select this, that from someTable where this is not null";
SqlCommand myCommand = new SqlCommand(dothis, myConnection);
try {
myCommand.Connection.Open();
myReader = myCommand.ExecuteReader(); //pretend "myReader" was declared earlier
} catch (Exception myEx) {
// left to your imagination, and googling.
}
finally {
myCommand.Connection.Close();
}
}
// do something with the results. Your's to google and figure out
概要是
您必须了解有关这些Sqlxxxxx类的更多信息,有很多方法可以将它们配置为执行您想要的操作。