不知道如何在数据库中添加值

时间:2014-12-29 12:37:27

标签: c# database

我有输入工作但现在我需要在每次输入数据库时​​添加原始数字,但我不知道该怎么做,任何帮助将不胜感激:)

String myConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:/coursework/Databases/runner database.accdb;"; // location of the database 
OleDbConnection myConnection = new OleDbConnection(myConnectionString); // To create the database connection
OleDbCommand myCommand = new OleDbCommand(); // Use the connection for the command
myCommand.Connection = myConnection;

try
{
    myConnection.Open(); // Opens the database connection
    string query = "insert into tblTrainingInformation ([Username],[Calories Burnt]) values('"+GlobalUsername.username+"','" + this.txtCaloriesBurntRun.Text + "')";
    OleDbCommand createCommand = new OleDbCommand(query, myConnection);
    createCommand.ExecuteNonQuery();
    MessageBox.Show("Your running information has been saved");
    myConnection.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

1 个答案:

答案 0 :(得分:0)

如果要更新现有记录,为字段添加新值或INSERT新记录(如果不存在),则需要知道数据库是否已包含Username。 因此,您需要先运行SELECT查询,然后再决定是否需要UPDATE或INSERT (Access没有像MySql或Sql Server那样的某种UPSERT语句)

String myConnectionString = ".....";
string querySel = @"SELECT [Username],[Calories Burnt] 
                    FROM tblTrainingInformation 
                    WHERE [Username] = @uname";
using(OleDbConnection myConnection = new OleDbConnection(myConnectionString))
using(OleDbCommand myCommand = new OleDbCommand(querySel, myConnection))
{
    myConnection.Open(); 
    myCommand.Parameters.AddWithValue("@uname", GlobalUsername.username);
    using(OleDbDataReader reader = myCommand.ExecuteReader())
    {
        int calories = 0;
        string query = "";
        if(reader.Read())
        {
            // The record exists, read the calories and add the new value
            // then execute the UPDATE 
            calories = Convert.ToInt32(reader["Calories Burnt"]);
            calories += Convert.ToInt32(this.txtCaloriesBurntRun.Text);
            query = @"UPDATE tblTrainingInformation 
                      SET [Calories Burnt] = @cal
                      WHERE [Username] = @uname";
        }
        else
        {
            // Record doesn't exist, INSERT the new data
            calories = Convert.ToInt32(this.txtCaloriesBurntRun.Text);
            query = @"INSERT INTO tblTrainingInformation 
                      ([Calories Burnt],[Username])
                      VALUES(@cal, @uname)";
        }
        reader.Close();
        myCommand.Parameters.Clear();
        myCommand.Parameters.AddWithValue("@cal", calories);
        myCommand.Parameters.AddWithValue("@uname", GlobalUsername.username);
        myCommand.ExecuteNonQuery();
        MessageBox.Show("Your running information has been saved");
    }
}

我在这里做了几个假设 首先我假设UserName是此表中的主键,因此您可以使用WHERE on username值检索记录。
第二个假设是字段Calories Burnt的类型 它应该是一个数字字段,为了简化示例,我认为它是一个整数。

如果这些假设不成立,则应检查并修复这些假设。

说,注意使用Using Statement来正确配置连接,命令和阅读器。从查询中删除字符串连接是另一个重点。您应该始终使用参数集合来避免Sql注入(尽管Access不太可能)以及解析值时出错。

关于参数顺序的最后说明。 OleDb想要参数占位符在查询文本中出现的确切顺序,所以我颠倒了INSERT的顺序以与UPDATE命令兼容