有没有办法让这个代码中插入数据库中的所有当前的数据?

问题描述 投票:-1回答:2

我想是所有从我的数据网格视图中的所有行和列中的数据插入到我的数据库。我没有得到任何错误,但是这是不工作不插入我的数据库中的任意值。

    con.Open();
    SqlCommand cmd = new SqlCommand();
    cmd = con.CreateCommand();
    for (int i = 0; i < dgEdit.Rows.Count; i++)
    {
       DateTime ds = DateTime.Now;
       cmd.CommandType = CommandType.Text;
       cmd.CommandText = "INSERT INTO Tb BL_Attendance(Course, Subject, 
       Year, Section, Name, Room, SeatNo, Status, Date) VALUES('" + 
       dgvAtt.Rows[i].Cells[0].Value + "', '" + 
       dgvAtt.Rows[i].Cells[1].Value + "', '" + 
       dgvAtt.Rows[i].Cells[2].Value + "', '" + 
       dgvAtt.Rows[i].Cells[3].Value + "', '" + 
       dgvAtt.Rows[i].Cells[4].Value + "', '" + 
       dgvAtt.Rows[i].Cells[5].Value + "', '" + 
       dgvAtt.Rows[i].Cells[6].Value + "', '" + 
       dgvAtt.Rows[i].Cells[7].Value + "', @Date) ";
       cmd.Parameters.AddWithValue("@Date", ds);
       cmd.ExecuteNonQuery();
    }
     MessageBox.Show("Updated! please check the report", "Save", 
     MessageBoxButtons.OK, MessageBoxIcon.Information);
     con.Close();

我期待这一切我DataGrid中值插入表

c# sql-server
2个回答
0
投票

你的原型是正确的,但你做了一个错误,dgvAtt.Rows[i].Cells[0].Value返回一个对象必须将它转换为ToString()或在您的表中的列数据,可以配合。

比方说,这是我的表单

let's say this my form

我创建了一个表“人” Person

源代码

private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            SqlCommand cmd = new SqlCommand();
            cmd = con.CreateCommand();
            for (int i = 0; i < dgvAtt.Rows.Count - 1; i++)
            {
                con.Open();
                cmd.CommandType = CommandType.Text;
                string Query = "INSERT INTO Person (idPerson, fullnamePerson) VALUES (" + dgvAtt.Rows[i].Cells[0].Value.ToString() + ",'" + dgvAtt.Rows[i].Cells[1].Value.ToString() + "')";
                cmd.CommandText = Query;
                cmd.ExecuteNonQuery();
                con.Close();
            }
            MessageBox.Show("Updated! please check the report", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

不要写任何参数,因为这会给你一个例外。


2
投票

下面的逻辑试图要尽可能靠近你实现,但考虑到的最佳实践与数据库连接时处理:

// You will need the following namespaces:
// using System;
// using System.Data;
// using System.Data.SqlClient;
// using System.Windows.Forms;

var connectionString = "Your SQL Server connection string";

using (var con = new SqlConnection(connectionString))
{
    con.Open();

    var cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText =
        "INSERT INTO Tbl_Attendance (Course, Subject, Year, Section, Name, Room, SeatNo, Status, Date) " +
        "VALUES (@Course, @Subject, @Year, @Section, @Name, @Room, @SeatNo, @Status, @Date)";

    var courseParam = cmd.Parameters.Add("@Course", SqlDbType.VarChar, 50);
    var subjectParam = cmd.Parameters.Add("@Subject", SqlDbType.VarChar, 50);
    var yearParam = cmd.Parameters.Add("@Year", SqlDbType.VarChar, 50);
    var sectionParam = cmd.Parameters.Add("@Section", SqlDbType.VarChar, 50);
    var nameParam = cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50);
    var roomParam = cmd.Parameters.Add("@Room", SqlDbType.VarChar, 50);
    var seatNoParam = cmd.Parameters.Add("@SeatNo", SqlDbType.VarChar, 50);
    var statusParam = cmd.Parameters.Add("@Status", SqlDbType.VarChar, 50);

    var dateParam = cmd.Parameters.Add("@Date", SqlDbType.DateTime);
    dateParam.Value = DateTime.Now;

    // If you are going to insert a lot of records, it's advised to call the Prepare method on your SqlCommand.
    // Un-comment the line below if you want to see how this behaves.
    // cmd.Prepare();

    foreach (DataGridViewRow row in dgEdit.Rows)
    {
        courseParam.Value = row.Cells[0].Value;
        subjectParam.Value = row.Cells[1].Value;
        yearParam.Value = row.Cells[2].Value;
        sectionParam.Value = row.Cells[3].Value;
        nameParam.Value = row.Cells[4].Value;
        roomParam.Value = row.Cells[5].Value;
        seatNoParam.Value = row.Cells[6].Value;
        statusParam.Value = row.Cells[7].Value;

        cmd.ExecuteNonQuery();
    }
}

MessageBox.Show("Updated! please check the report", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);

变化背后的原因:

  • 如果可能的话,实例化并打开一个using语句中的SqlConnection的连接。这将确保您的连接总是关闭(设置),当你与它的范围进行。
  • 在查询与任何外部输入交互时,一定要使用参数,以避免鲍比的母亲利用! (https://xkcd.com/327/)。这将确保你的代码是不容易受到SQL注入。正如你所看到的,我加了一些参数,而是因为你没有提供你的表模式我发再与VARCHAR(50)一个地方很显然,您要保存@Date除外System.DateTime。请随时向SqlDbType.VarChar更改为正确的类型需要的地方。
  • 我搬到了调用MessageBox.Show范围之外using因此它不会与连接处理干扰。

你可以做这样的逻辑正在实施利用System.Transactions.TransactionScope类的另一种增强(必须添加到System.Transactions.dll参考),以确保如果有在任何插件的错误,没有得到committed到数据库。

© www.soinside.com 2019 - 2024. All rights reserved.