应编写什么代码,以便不应插入相同的代码 [英] what code should be written so that same code should not be inserted

查看:61
本文介绍了应编写什么代码,以便不应插入相同的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应编写哪些代码,以便不应在数据库中再次插入相同的数据。

解决方案

根据您的尝试,有不同的方法;



1)标记数据库架构,使字段必须唯一,是主键等。



2)从数据构建哈希并将数据存储为字段。创建新记录时,计算哈希并尝试保存新数据。哈希字段必须标记为唯一。



3)提出自己检查唯一性的方法。


假设你的数据库包含名为username的字段,然后您可以检查数据库中是否存在用户名,如果没有,则输入详细信息,否则抛出异常。示例如下。



 SqlConnection conn =  new  SqlConnection(); 
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings [ 连接字符串名称] .ConnectionString;
conn.Open();
String user = TextBox1.Text;
SqlCommand check = new SqlCommand( select *来自table_name,其中name = @ user,conn);
cmd.Parameters.Add( new SqlParameter( @user,用户));
SqlDataReader reader = check.ExecuteReader();
if (!reader.Read())
{
/ * 将详细信息插入数据库* /
}
else
{
/ * 抛出异常* /
}


what code should be written so that same data should not be inserted again in database.

解决方案

There are different approaches depending on what you are trying to do;

1) Mark the database schema such that fields must be unique, are primary keys etc.

2) Build a hash from the data and store that with the data as a field. When you create a new record calculate the hash and try and save the new data. The hash field must be marked unique.

3) Come up with your own method of checking for uniqueness.


Suppose your database contains field called username,then you can check if username exist in the database or not,if not then enter the details else throw an exception.Example is given below.

SqlConnection conn = new SqlConnection();
 conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["connection string name"].ConnectionString;
 conn.Open();
 String user=TextBox1.Text;
 SqlCommand check = new SqlCommand("select * from table_name where name=@user", conn);
 cmd.Parameters.Add(new SqlParameter("@user",user));
 SqlDataReader reader = check.ExecuteReader();
 if (!reader.Read())
 {
        /*Insert details into database*/
 }
 else
 {
       /*Throw en Exception*/
 }


这篇关于应编写什么代码,以便不应插入相同的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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