在通过C#插入数据之前,如何检查表。 [英] How Can I Check Table Before I Insert Data By C#.

查看:59
本文介绍了在通过C#插入数据之前,如何检查表。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

protected void btnRegister_Click(object sender, EventArgs e)
        {
            string connetionString = "Data Source=qweq;Initial Catalog=Test_DB;User ID=asd;Password=asdsf";
            SqlConnection conn = new
            SqlConnection(connetionString);
            string commText = "insert into login(User_Name,Password,Address,City,State,PIN,Phone_no,Email_id,Created_By,Created_on) values('" + txtUserName.Text + "','" + txtPassword.Text + "','" + txtAddress.Text + "','" + txtCity.Text + "','" + txtState.Text + "','" + Convert.ToDouble(txtPin.Text) + "','" + Convert.ToDouble(txtPhoneNo.Text) + "','" + txtEmailId.Text +  "','" + "Alok" + "','" + DateTime.Now + "')";
            SqlCommand cmd = new 
            SqlCommand(commText, conn);
            conn.Open();
            int no = cmd.ExecuteNonQuery();
            conn.Close();
            if(no>0)
            {
                Label1.Text= "User register register sucessfully";
            }
            else
            {
                Label1.Text = "Error";
            }
            txtUserName.Text = String.Empty;
            txtPassword.Text = String.Empty;
            txtAddress.Text = String.Empty;
            txtCity.Text = String.Empty;
            txtState.Text = String.Empty;
            txtPin.Text = String.Empty;
            txtPhoneNo.Text = String.Empty;
            txtEmailId.Text = String.Empty;

        }







编辑:代码块添加




Edited: Code block Added

推荐答案

使用 EXISTS

Use EXISTS
if not exists (select *from login where username=@username) 
begin
--Insert Query
end
else 
begin
--Update Query or something..
end



请参考

http://www.java2s.com/Tutorial/SQLServer/0400_ _Transact-SQL / IFEXISTS.htm [ ^ ]


这个链接可以帮你做。



http://stackoverflow.com/questions/18114458/fastest-way-to-determine-if-record-存在 [ ^ ]



注意:附加字符串不是一个好习惯,因为它暴露给Sql注入。将此转换为存储过程或参数化查询请参阅链接 http://rosettacode.org/wiki/Parametrized_SQL_statement [ ^ ]
Might be this link will help you do it.

http://stackoverflow.com/questions/18114458/fastest-way-to-determine-if-record-exists[^]

NOTE: Appending string is not a good practice as it exposes to Sql injection. Either convert this to stored procedure or paramaterized query see link http://rosettacode.org/wiki/Parametrized_SQL_statement[^]


只需编写更多sql,如:



从登录处选择计数(*),其中username = username



如果计数为0那么你就是很高兴。
Just write some more sql like:

select count(*) from login where username = username

If the count is 0 then you're good to go.


这篇关于在通过C#插入数据之前,如何检查表。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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