插入数据不保存在DB中? [英] insertion data not save in DB?

查看:66
本文介绍了插入数据不保存在DB中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即时尝试将数据插入到数据库中,这是我的代码,每件事都很好没有错误问题是只是插入数据不保存在我的DataBase1.mdf中我不知道为什么?

当我的程序运行时,第一次插入数据时,它们显示在gridView1中但不存储在database1.mdf中

任何人都帮我

数据库名称:inventry

表名:addProduct

栏:pid,title,descrtion,type,vendor,price,isbn





app.config文件



im trying to data insert into database, this is my code every thing is fine no error The problem is that just insertion data not save in my DataBase1.mdf i dont know why?
When my program is running, the first time that I insert data, they show in gridView1 but not store in database1.mdf
anyone help me
DB name : inventry
table name: addProduct
column : pid,title,descrtion,type,vendor,price,isbn


app.config file

<connectionStrings>
        <add name="inven" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\inventry.mdf;Integrated Security=True;User Instance=True" />
    </connectionStrings>







按钮代码文件






Button code file

private void button1_Click(object sender, EventArgs e)
        {
            String con = ConfigurationManager.ConnectionStrings["inven"].ConnectionString;

            SqlConnection connection = new SqlConnection(con);

            connection.Open();
  SqlCommand cmd = new SqlCommand("Insert into addProduct(title,descrtion,type,vendor,price,isbn) values(@title,@descrtion,@type,@vendor,@price,@isbn)", connection);

            cmd.Parameters.AddWithValue("@title", textBox1.Text);
            cmd.Parameters.AddWithValue("@descrtion", textBox2.Text);
            cmd.Parameters.AddWithValue("@type", textBox3.Text);
            cmd.Parameters.AddWithValue("@vendor", textBox4.Text);
            cmd.Parameters.AddWithValue("@price", textBox5.Text);
            cmd.Parameters.AddWithValue("@isbn", textBox6.Text);

            int rows = cmd.ExecuteNonQuery();
            if (rows != 0)
            {
                MessageBox.Show("Inserted");
            }
            else
            {
                MessageBox.Show("Insertion failure");
            }
           connection.Close();
}

推荐答案

检查加载事件:当用户单击按钮时,在Click事件之前触发加载事件,所以如果你明确地清楚(或设置任何值)你的Load事件处理程序中的文本框,那些将是它插入数据库的值。



修复检查 IsPostBack [ ^ ]属性,只有在为false时才进行初始化。
Check you Load event: When the user clicks a button, the load event is fired before the Click event, so if you specifically clear (or set any values into) the textboxes in you Load event handler, those will be that values it inserts to the database.

To fix that, check the IsPostBack[^] property, and only do such initialisations when it is false.


protected void Page_Load(object sender, EventArgs e)
{
    // Please check the OG's Answer why this is important
    if (!IsPostBack)
    {
        // load data in page load only in first time
        LoadData();
    }
}

private void LoadData()
{
    //Load data from database and bind it to gridview
}

protected void Button1_Click(object sender, EventArgs e)
{
    String constring = ConfigurationManager.ConnectionStrings["inven"].ConnectionString;
    //use [] for the column names if those are reserved sql keywords like description, type etc..
    string insertSql = "insert into addProduct([title],[descrtion],[type],[vendor],[price],[isbn]) values(@title,@descrtion,@type,@vendor,@price,@isbn)";

    using (SqlConnection connection = new SqlConnection(constring))
    using (SqlCommand cmd = new SqlCommand(insertSql, connection))
    {
        cmd.Parameters.AddWithValue("@title", textBox1.Text);
        cmd.Parameters.AddWithValue("@descrtion", textBox2.Text);
        cmd.Parameters.AddWithValue("@type", textBox3.Text);
        cmd.Parameters.AddWithValue("@vendor", textBox4.Text);
        cmd.Parameters.AddWithValue("@price", textBox5.Text);
        cmd.Parameters.AddWithValue("@isbn", textBox6.Text);
        connection.Open();
        int rows = cmd.ExecuteNonQuery();
        string message = "Insertion failure";
        if (rows > 0)
        {
            message = "Inserted";
        }
        //MessageBox.Show will not work in ASP.NET, use below
        ClientScript.RegisterStartupScript(this.GetType(), "Message", "alert('" + message + "');", true);
        //load newly added data to gridview
        LoadData();
    }
}





更新

======


右键单击解决方案资源管理器中的数据库文件,如果没有,则选择构建操作作为副本。我认为下次运行时你的数据会丢失,因为视觉研究会用新的数据库替换旧的数据库。



UPDATE
======

right click on your database file in solution explorer and select build action as copy if never. I think your data lost when you run next time because of the visual study replace old database with new one.






你的代码是正确的,工作正常....



问题出在你处于调试模式发布模式时 ...



程序运行时自动创建数据库文件..您插入的数据存储在该文件夹中..inside BIN



请检查Bin文件夹中的Debug文件夹,您将使用插入的数据查找Access数据库文件...



工作代码下方...适用于Windows /桌面应用程序



Hi,

Your code is correct and working fine....

The problem is when you are in Debug Mode or Release mode...

Database file created automatically when the program is running.. and the data you have inserted is stored in that folder..inside BIN

Please check the Debug folder inside Bin folder, you will fin the Access database file with your inserted data...

Below the working code...for windows/ desktop application

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WFDS
{
    public partial class AccessDB : Form
    {
         OleDbConnection conn = new OleDbConnection();
         String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Data\\BookStore.accdb;Persist Security Info=True";
        public AccessDB()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            try
            {
              
                conn.Open();




                OleDbCommand cmd = new OleDbCommand("Insert into product(title,descrtion,type,vendor,price,isbn) values(@title,@descrtion,@type,@vendor,@price,@isbn)", conn);

                cmd.Parameters.AddWithValue("@title", textBox1.Text);
                cmd.Parameters.AddWithValue("@descrtion", textBox2.Text);
                cmd.Parameters.AddWithValue("@type", textBox3.Text);
                cmd.Parameters.AddWithValue("@vendor", textBox4.Text);
                cmd.Parameters.AddWithValue("@price", textBox5.Text);
                cmd.Parameters.AddWithValue("@isbn", textBox6.Text);

                int rows = cmd.ExecuteNonQuery();
                if (rows != 0)
                {
                    MessageBox.Show("Inserted");
                }
                else
                {
                    MessageBox.Show("Insertion failure");
                }
                conn.Close();



            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
 
   
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string sql = "SELECT *  FROM product";
            DataSet ds = new DataSet();
           
          
            OleDbDataAdapter adapter = new OleDbDataAdapter(sql, conn);
            adapter.Fill(ds);
            int dd = ds.Tables[0].Rows.Count;
            dataGridView1.DataSource = ds.Tables[0];
            conn.Close();
           
        }

        private void AccessDB_Load(object sender, EventArgs e)
        {
            conn.ConnectionString = connection;
        }
    }
}









数据库文件存储在 Bin \Debug BIN \Release 目录中



谢谢,



Ullas Krishnann





The database file is stored in the Bin\Debug or BIN\Release directory

Thanks,

Ullas Krishnann


这篇关于插入数据不保存在DB中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆