C# 在SQL Server表中查找唯一行

C# 在SQL Server表中查找唯一行,c#,sql-server,C#,Sql Server,我在这里看一个例子: 它们没有指定dataSet1来自何处,这是否表示某个数据库 我试图在代码中使用这个示例来查找唯一的行,但我似乎无法实现这个语法。我只使用连接字符串打开到SQL的连接,我使用SqlDataAdapter执行函数 编辑: SqlConnection myConnection=newsqlconnection(“数据源=server;初始目录=Dashboard;集成安全=SSPI;持久安全信息=false;可信连接=Yes”); SqlDataAdapter da=新的Sql

我在这里看一个例子:

它们没有指定
dataSet1
来自何处,这是否表示某个数据库

我试图在代码中使用这个示例来查找唯一的行,但我似乎无法实现这个语法。我只使用连接字符串打开到SQL的连接,我使用
SqlDataAdapter
执行函数

编辑:

SqlConnection myConnection=newsqlconnection(“数据源=server;初始目录=Dashboard;集成安全=SSPI;持久安全信息=false;可信连接=Yes”);
SqlDataAdapter da=新的SqlDataAdapter();
尝试
{
//打开与指定数据库的连接
myConnection.Open();
//指定在数据库中输入数据的表的位置和使用的列
da.InsertCommand=new SqlCommand(“插入仪表板libanswer(Id、日期、时间、问题、详细信息、答案、备注、输入者、接收地点、问题类型、应答方法、交易持续时间)”
+“值(@Id、@Date、@Time、@Question、@Details、@Answer、@Notes、@EnteredBy、@WhereReceived、@QuestionType、@AnswerMethod、@TransactionDuration)”,myConnection);
//指定将在其中输入数据的列及其变量类型
//特别注意:从字符串>日期时间转换将导致异常,这些异常只导入部分数据,而不是全部数据
Add(“@Id”,SqlDbType.NVarChar);
Add(“@Date”,SqlDbType.Text);
Add(“@Time”,SqlDbType.Text);
Add(“@Question”,SqlDbType.Text);
Add(“@Details”,SqlDbType.Text);
Add(“@Answer”,SqlDbType.Text);
添加(“@Notes”,SqlDbType.Text);
Add(“@EnteredBy”,SqlDbType.NVarChar);
Add(“@WhereReceived”,SqlDbType.NVarChar);
Add(“@QuestionType”,SqlDbType.NVarChar);
Add(“@AnswerMethod”,SqlDbType.NVarChar);
Add(“@TransactionDuration”,SqlDbType.NVarChar);
//使用全局变量计数器,此循环将遍历每个有效条目,并将其插入指定的数据库/表中
对于(int i=0;i
如果从数据适配器填充数据集,则可以遵循相同的逻辑-

这可能值得展示您需要获得更具体帮助的实际情况

编辑 我想我已经理解了您的需求-如果您从已经填充的表中填充数据表,只需在添加它之前检查该项是否已经存在-即

if (dt.Rows.Find(collection.getIdItems(i)) == null)    
{
    // add your new row
}
(为了确保我完成了一个快速测试——希望这能有所帮助):

//MyContacts db有一个主键为(ID)的表Person-3行-ID4,5,6
SqlConnection myConnection=newsqlconnection(“数据源=;初始目录=MyContacts;集成安全=SSPI;持久安全信息=false;可信连接=Yes”);
SqlDataAdapter da=新的SqlDataAdapter();
da.SelectCommand=新的SqlCommand(“选择*来自个人”,myConnection);
myConnection.Open();
数据集仪表板DS=新数据集();
da.填写(仪表盘,“人员”);
SqlConnection myConnection = new SqlConnection("Data Source=server; Initial Catalog=Dashboard; Integrated Security=SSPI; Persist Security Info=false; Trusted_Connection=Yes");
SqlDataAdapter da = new SqlDataAdapter();

try
        {
            //Opens the connection to the specified database
            myConnection.Open();

            //Specifies where the Table in the database where the data will be entered and the columns used
            da.InsertCommand = new SqlCommand("INSERT INTO DashboardLibAnswer(Id,Date,Time,Question,Details,Answer,Notes,EnteredBy,WhereReceived,QuestionType,AnswerMethod,TransactionDuration)"
                + "VALUES(@Id,@Date,@Time,@Question,@Details,@Answer,@Notes,@EnteredBy,@WhereReceived,@QuestionType,@AnswerMethod,@TransactionDuration)", myConnection);

            //Specifies the columns and their variable type where the data will be entered
            //Special note:  Conversion from String > DateTime will cause exceptions that will only import some part of data and not everything
            da.InsertCommand.Parameters.Add("@Id", SqlDbType.NVarChar);
            da.InsertCommand.Parameters.Add("@Date", SqlDbType.Text);
            da.InsertCommand.Parameters.Add("@Time", SqlDbType.Text);
            da.InsertCommand.Parameters.Add("@Question", SqlDbType.Text);
            da.InsertCommand.Parameters.Add("@Details", SqlDbType.Text);
            da.InsertCommand.Parameters.Add("@Answer", SqlDbType.Text);
            da.InsertCommand.Parameters.Add("@Notes", SqlDbType.Text);
            da.InsertCommand.Parameters.Add("@EnteredBy", SqlDbType.NVarChar);
            da.InsertCommand.Parameters.Add("@WhereReceived", SqlDbType.NVarChar);
            da.InsertCommand.Parameters.Add("@QuestionType", SqlDbType.NVarChar);
            da.InsertCommand.Parameters.Add("@AnswerMethod", SqlDbType.NVarChar);
            da.InsertCommand.Parameters.Add("@TransactionDuration", SqlDbType.NVarChar);

            //Using the global variable counter this loop will go through each valid entry and insert it into the specifed database/table
            for (int i = 0; i < counter; i++)
            {
                //Iterates through the collection array starting at first index and going through until the end
                //and inserting each element into our SQL Table

                DataSet dashboardDS = new DataSet();
                da.Fill(dashboardDS, "DashboardLibAnswer");

                DataTable dt = dashboardDS.Tables["DashboardLibAnswer"];

                foreach (DataColumn col in dt.Columns)
                {
                    if (col.Unique)
                    {
                        da.InsertCommand.Parameters["@Id"].Value = collection.getIdItems(i);
                        da.InsertCommand.Parameters["@Date"].Value = collection.getDateItems(i);
                        da.InsertCommand.Parameters["@Time"].Value = collection.getTimeItems(i);
                        da.InsertCommand.Parameters["@Question"].Value = collection.getQuestionItems(i);
                        da.InsertCommand.Parameters["@Details"].Value = collection.getDetailsItems(i);
                        da.InsertCommand.Parameters["@Answer"].Value = collection.getAnswerItems(i);
                        da.InsertCommand.Parameters["@Notes"].Value = collection.getNotesItems(i);
                        da.InsertCommand.Parameters["@EnteredBy"].Value = collection.getEnteredByItems(i);
                        da.InsertCommand.Parameters["@WhereReceived"].Value = collection.getWhereItems(i);
                        da.InsertCommand.Parameters["@QuestionType"].Value = collection.getQuestionTypeItems(i);
                        da.InsertCommand.Parameters["@AnswerMethod"].Value = collection.getAnswerMethodItems(i);
                        da.InsertCommand.Parameters["@TransactionDuration"].Value = collection.getTransactionItems(i);
                        da.InsertCommand.ExecuteNonQuery();
                    }
                }

                //Updates the progress bar using the i in addition to 1 
                _worker.ReportProgress(i + 1);

            } // end for

            //Once the importing is done it will show the appropriate message
            MessageBox.Show("Finished Importing");

        } // end try
        catch (Exception exceptionError)
        {
            //To show exceptions thrown just uncomment bellow line
            //rtbOutput.AppendText(exceptionError.ToString);

        } // end catch

        //Closes the SQL connection after importing is done
        myConnection.Close();

    }
if (dt.Rows.Find(collection.getIdItems(i)) == null)    
{
    // add your new row
}
  // MyContacts db has a table Person with primary key (ID) - 3 rows - IDs 4,5,6
  SqlConnection myConnection = new SqlConnection("Data Source=.; Initial Catalog=MyContacts; Integrated Security=SSPI; Persist Security Info=false; Trusted_Connection=Yes");
        SqlDataAdapter da = new SqlDataAdapter();

        da.SelectCommand = new SqlCommand("select * from Person", myConnection);

        myConnection.Open();

        DataSet dashboardDS = new DataSet();
        da.Fill(dashboardDS, "Person");

        dashboardDS.Tables[0].PrimaryKey = new[] { dashboardDS.Tables[0].Columns["ID"]}; 

        List<int> ids = new List<int> {4, 6, 7};

        foreach (var id in ids)
        {
            if (dashboardDS.Tables[0].Rows.Find(id) == null)
            {
                Console.WriteLine("id not in database {0}", id); //i.e. 7
            }
        }
string connString =
            "server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";
string sql = @"SELECT TOP 1 * FROM AnyTable";
using (SqlConnection conn = new SqlConnection(connString)) {
    conn.Open();
    SqlDataAdapter da = new SqlDataAdapter(sql, conn);
    using (DataSet ds = new DataSet()) {
        da.Fill(ds, "AnyTable");
        DataTable dt = ds.Tables["AnyTable"];
        foreach (DataColumn col in dt.Columns) {
            if (col.Unique) {
                Console.WriteLine("Column {0} is unique.", col.ColumnName);
            }
        }
    }
}
SELECT DISTINCT field1, field2, field3 FROM AnyTable
foreach (var item in collection.Distinct()) {

}
string[] lines = File.ReadAllLines(@"C:\Data\MyData.csv");
string[][] splittedLines = lines
                .Distinct()
                .Select(s => s.Split(','))
                .ToArray();