为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
慕妹3146593 2022-08-20 17:44:29
我想要的是将数据网格视图中所有行和列中的所有数据插入到我的数据库中。我没有收到任何错误,但这不起作用,没有在我的数据库中插入任何值。    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();我期望这将我的所有数据网格值插入到表中
查看完整描述

2 回答

?
忽然笑

TA贡献1806条经验 获得超5个赞

下面的逻辑尝试尽可能接近您的实现,但在处理数据库连接时要考虑最佳实践:


// 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);

更改背后的原因:

  • 如果可能,请在语句中实例化并打开 SqlConnection 连接。这将确保在作用域中完成连接时,始终关闭(释放)连接。using

  • 在与任何外部输入交互时,始终在查询中使用参数,以避免Bobby的妈妈被利用!(https://xkcd.com/327/)。这将确保您的代码不容易受到 SQL 注入的影响。如您所见,我添加了一些参数,但是由于您没有提供我当时创建的表架构,因此除了很明显您正在保存.请根据需要随意将 更改为正确的类型。VARCHAR(50)@DateSystem.DateTimeSqlDbType.VarChar

  • 我将呼叫移到了范围之外,因此它不会干扰连接处理。MessageBox.Showusing

可以对此逻辑执行的另一项增强功能是实现类的使用(必须添加对 System.Transactions 的引用.dll),以确保如果在任何插入过程中出现错误,则没有任何内容进入数据库。System.Transactions.TransactionScopecommitted


查看完整回答
反对 回复 2022-08-20
?
至尊宝的传说

TA贡献1789条经验 获得超10个赞

您的原型是正确的,但您犯了一个错误,返回一个 Object,必须将其转换为或表中可能匹配的列数据。dgvAtt.Rows[i].Cells[0].ValueToString()

假设这是我的形式

//img1.sycdn.imooc.com//6300ad24000197c606790461.jpg

我创建了一个表“人员”

//img1.sycdn.imooc.com//6300ad3300013c9506430116.jpg

代码源码


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);

        }

    }

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


查看完整回答
反对 回复 2022-08-20
  • 2 回答
  • 0 关注
  • 153 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号