简体   繁体   English

SqlDataAdapter插入数据库不起作用C#winform

[英]SqlDataAdapter Insert Database not working C# winform

I am trying to insert data into a SQL Server database and show on DatagridView from a C# Winforms. 我正在尝试将数据插入SQL Server数据库并从C#Winforms在DatagridView上显示。

I click on the Insert button no error shows, but no data is being Insert into the database and Datagridview becomes blank. 我单击“插入”按钮,没有错误显示,但是没有数据正在插入数据库,并且Datagridview变为空白。

I re-debug that can see data update in datagridview, but the database is not on Visual Studio Server Explorer DataBase(picture1). 我重新调试可以在datagridview中看到数据更新,但是数据库不在Visual Studio Server Explorer数据库(picture1)上。

On the other hand.I set breakpoint when click Insert Button,that jump over line 42~46.Directly to line 50.ex(picture2). 另一方面,当我单击“插入按钮”时设置了断点,它会跳过第42〜46行。直接跳到第50.ex(picture2)行。

picture1 图片1

picture2 图片2

Edit : The question now is when I click insert button,datagridview have update new data.But database no insert new data.Database only two data. 编辑 :现在的问题是当我单击插入按钮时,datagridview有更新新数据。但是数据库没有插入新数据。数据库只有两个数据。

Edit2 I changed connection string AttachDbFilename. Edit2我更改了连接字符串AttachDbFilename。 AttachDbFilename=C:\\Vis\\NO4\\WindowsFormsApplication1\\App_Dat‌​a\\Database1.mdf; The value can insert database. 该值可以插入数据库。

Here is the connection string: 这是连接字符串:

<add name="con1" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True"
        providerName="System.Data.SqlClient" />

Here is the Form_load and load_grid function 这是Form_load和load_grid函数

SqlConnection con;
    SqlDataAdapter da;
    DataSet ds = new DataSet();
    DataTable dt = new DataTable();
    public Form1()
    {
        InitializeComponent();
        string connectionString = ConfigurationManager.ConnectionStrings["con1"].ConnectionString;
        con = new SqlConnection(connectionString);

    }

    private void Form1_Load(object sender, EventArgs e)
    {
       load_grid();
    }
    public void load_grid()
    {
        dt.Clear();
        SqlDataAdapter da1 = new SqlDataAdapter();
        try
        {
            string sql = "SELECT * FROM profile";
            con.Open();
            da1.SelectCommand = new SqlCommand(sql, con);
            da1.Fill(ds);
            da1.Fill(dt);
            con.Close();
            dataGridView1.DataSource = dt;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Here is the Insert Button 这是插入按钮

 private void button1_Click(object sender, EventArgs e)
    {
        string ac = textBox1.Text;
        string bd = textBox2.Text;
        string sex = textBox2.Text;
        string sql = "INSERT INTO profile(ac,bd,sex)VALUES('" + ac + "','" + bd + "','" + sex + "')";
        try
        {
            con.Open();
            da = new SqlDataAdapter();
            da.InsertCommand = new SqlCommand(sql, con);
            da.InsertCommand.ExecuteNonQuery();
            da.Update(dt);
            MessageBox.Show("INsert success...!!");
            load_grid();
            con.Close();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Here is the design of the Costumer table 这是Costumer表的设计

CREATE TABLE [dbo].[profile] (
[Id]  INT           IDENTITY (1, 1) NOT NULL,
[ac]  NVARCHAR (50) NULL,
[bd]  NVARCHAR (50) NULL,
[sex] NVARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC));

Not sure where the issue is here. 不知道问题出在哪里。

Picture2 shows an exception that connection is already open so, try following before opening a connection. Picture2显示了一个连接已经打开的异常,因此,在打开连接之前尝试以下操作。 You are calling load_grid(); 您正在调用load_grid(); before closing connection. 在关闭连接之前。 I have update all code, use it as explained below: 我已经更新了所有代码,如下所述使用它:

Edit- Second Revision: 编辑第二次修订:

public void load_grid()
    {
        dt.Clear();
        SqlDataAdapter da1 = new SqlDataAdapter();
        try
        {
            string sql = "SELECT * FROM profile";
            con.Open();
            da1.SelectCommand = new SqlCommand(sql, con);
            da1.Fill(ds);
            da1.Fill(dt);
            con.Close();
            dataGridView1.DataSource = dt;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            if (con.State != System.Data.ConnectionState.Closed)
                con.Close();
        }
    }


 private void button1_Click(object sender, EventArgs e)
        {
            string ac = textBox1.Text;
            string bd = textBox2.Text;
            string sex = textBox2.Text;
            string sql = "INSERT INTO profile(ac,bd,sex)VALUES('" + ac + "','" + bd + "','" + sex + "')";
            try
            {
                con.Open();
                da = new SqlDataAdapter();
                da.InsertCommand = new SqlCommand(sql, con);
                da.InsertCommand.ExecuteNonQuery();
                da.Update(dt);
                con.Close();
                MessageBox.Show("INsert success...!!");
                load_grid();               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (con.State != System.Data.ConnectionState.Closed)
                    con.Close();
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM