在C#问题中向数据库添加数据 [英] Adding data to database in C# problem

查看:108
本文介绍了在C#问题中向数据库添加数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string connection = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated Security=True;User Instance=True";
        SqlConnection cn = new SqlConnection(connection);
        cn.Open();

        string sqlquery = "INSERT INTO [users] (member, pass) VALUES (@memb ,@pas)";

        SqlCommand cmd = new SqlCommand(sqlquery, cn);

        cmd.Parameters.AddWithValue("@memb", SqlDbType.VarChar).Value = textBox1.Text;
        cmd.Parameters.AddWithValue("@pas", SqlDbType.VarChar).Value = textBox2.Text;

        int i = (int)cmd.ExecuteNonQuery();

        if (i > 0)
        {
            this.Close();
            Form2 form2 = new Form2();
            form2.Show();
            MessageBox.Show("Data updated", "Adding data", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
        else
        {
            MessageBox.Show("Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        cn.Close();



有人可以向我解释为什么它不向数据库添加数据吗?



Can someone explain it to me, why it doesn''t add data to database ?

推荐答案

hi,

这篇文章描述了一些类似的问题: http://stackoverflow.com/questions/3317868/insert -problem-in-c-using-sqlcommand [ ^ ]

我也建议移动cn.Close();.到以下


This post described somewhat similar problem: http://stackoverflow.com/questions/3317868/insert-problem-in-c-using-sqlcommand[^]

I would also suggest to move cn.Close(); to below
int i = (int)cmd.ExecuteNonQuery();

,因为如果我> 0

because the cn.Close() method never get call if i > 0


您的数据库意味着Database1.mdf需要一些配置.

1. Database1.mdf应该放置在应用程序的Bin \ dubug文件夹中.

2.选择Database1.mdf,按F4打开属性窗口. 复制到输出目录"应设置为不复制".
它可能会产生错误,因此第一次将其更改为如果更新则复制",然后将其更改为请勿复制".



您编写的代码没有问题.
希望对您有帮助.
祝您编码愉快.
your Database means Database1.mdf required some configurations.

1. The Database1.mdf should be placed within Bin\dubug folder of your application.

2. Select Database1.mdf, open properties windows by pressing F4. the "Copy to Output Directory " should be set as "Do not copy".
it may generate error so first time change it to "Copy if newer" then change it to "Do not copy".



There is no Problem with the code written by you.
Hope this will help you.
Happy Coding.


您正在使用本地数据库.您只需尝试使用SqlParameter的新对象.否则没关系...
You are using local database. You just try with the new object of SqlParameter. Otherwise it is ok...


这篇关于在C#问题中向数据库添加数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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