C#将数据插入数据库 [英] C# insert data to DB

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

问题描述

此代码有什么问题,因为我无法将数据插入到基于服务的数据库中.数据库连接正常,因此从catch语法的末尾开始,代码一定存在问题

What is wrong with this code, because i can''t insert data to my service-based DB. DB connect is OK so something must be wrong with code next from the end ofthe catch syntax

string cn=@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
            SqlConnection connection = new SqlConnection(cn);
            SqlDataAdapter adapter = new SqlDataAdapter();
            SqlCommand command = new SqlCommand();
            try
            {
                connection.Open();
            }
            catch (Exception)
            {
                MessageBox.Show("ERROR");
                connection.Close();
            
            }
            command = new SqlCommand("SELECT * FROM users",connection);
            adapter.SelectCommand = command;
            command = new SqlCommand("INSERT INTO users(uname,pass,mail)"+
            "VALUES(@uname,@pass,@mail)",connection);
            //
            command.Parameters.Add("@uname", tBuime.Text);
            command.Parameters.Add("@pass", tBgeslo.Text);
            command.Parameters.Add("@mail", tBeposta.Text);
            //
            adapter.InsertCommand = command;
            connection.Close();




感谢您的帮助!




Thanx for help !

推荐答案

您不需要adapter.只要做一个
You do not need the adapter. Just do a
command.ExecuteNonQuery();


使用此代码

Use this code

command.Parameters.Add("@uname", tBuime.Text);
            command.Parameters.Add("@pass", tBgeslo.Text);
            command.Parameters.Add("@mail", tBeposta.Text);
            //
            adapter.InsertCommand = command;
            //added line  
            adapter.InsertCommand.ExecuteNonQuery();
            //added line ENDS HERE 
            connection.Close();



希望这能对您有所帮助,然后接受此答案
谢谢...



Hope this will help you if it works fine then accept this answer
Thanks...


您必须致电
You have to call
adapter.Update


关闭连接之前执行插入命令的方法


method to execute the insert command before closing the connection


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

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