简体   繁体   English

想要以C#语法将数据添加到sql server中的多个表中

[英]add data into more than one table in sql server in c# syntax wanted

I have 2 tables in my database and I need to save the data to both tables in one method. 我的数据库中有2个表,我需要用一种方法将数据保存到两个表中。 I am getting an code unreachable error when I execute the following method. 执行以下方法时,出现代码无法到达错误。 I need someone to tell me how to add this statement as a single insert statement. 我需要有人告诉我如何将此语句添加为单个插入语句。 By the way PC_QA_REPORT_1 has a primary key and PC_QA_REPORT_2 has a foreign key to it, with Project_ID being a common column in both tables for this purpose. 顺便说一下,PC_QA_REPORT_1有一个主键,而PC_QA_REPORT_2有一个外键,为此,Project_ID是两个表中的公用列。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data.SqlClient;
using System.Xml;
using System.IO;
using System.Data;

namespace WcfService2
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class Service1 : IService1
    {
        SqlConnection con = new SqlConnection("server = SP-DEV-MACHINE; Initial Catalog=The_Performance; Integrated Security=True");

        //public string GetData(int value)
        //{
        //    return string.Format("You entered: {0}", value);
        //}
        public string SubmitData(string pid, string ptitle, string date, string pqr, string pd, string ps, string pr, string pme, string pef, string pet, string psno, string pqs, string pds, string pmd, string pmr, string pmn)
        {



            SqlCommand cmd = new SqlCommand("INSERT INTO PC_QA_REPORT_1  (Project_ID, Project_Title, Date, Project_Quality_Rating, Project_Decision, Project_Strategic, Project_Relevant, Project_Monitoring_Eval, Project_Efficient, Project_Effective, Project_Sus_Nat_Own, Project_QA_Summary, Project_Document_Status) VALUES('" + pid + "','" + ptitle + "','" + date + "','" + pqr + "','" + pd + "','" + ps + "','" + pr + "','" + pme + "','" + pef + "','" + pet + "','" + psno + "','" + pqs + "','" + pds + "')", con);
            SqlCommand command = new SqlCommand("INSERT INTO PC_QA_REPORT_2 (Project_M_Date, Project_M_Responsibility,Project_M_Notes) VALUES('" + pmd + "','" + pmr + "','" + pmn + "')", con);

            con.Open();

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

            con.Close();
            return i.ToString();
            return x.ToString();

        }
        //public string MoreData(string pmd, string pmr, string pmn)
        //{

        //    SqlCommand command = new SqlCommand("INSERT INTO PC_QA_REPORT_2 (Project_M_Date, Project_M_Responsibility,Project_M_Notes) VALUES('" + pmd + "','" + pmr + "','" + pmn + "')", con);
        //    con.Open();
        //    int x = command.ExecuteNonQuery();
        //    con.Close();
        //    return x.ToString();
        //}

    }
}

You can't insert into two tables without using two INSERT statements. 不使用两个INSERT语句就不能插入两个表中。 It's just not possible. 只是不可能。 But you can put two INSERT statements into the same sql command object and run them in one transaction: 但是您可以将两个INSERT语句放入同一个sql命令对象中,并在一个事务中运行它们:

public int SubmitData(string pid, string ptitle, string date, string pqr, string pd, string ps, string pr, string pme, string pef, string pet, string psno, string pqs, string pds, string pmd, string pmr, string pmn)
{
    string sql = 
       "BEGIN TRANSACTION; " +

       "DECLARE @result int;"
       "INSERT INTO PC_QA_REPORT_1 (" +
         " Project_ID, Project_Title, Date, Project_Quality_Rating, Project_Decision, " +
         " Project_Strategic, Project_Relevant, Project_Monitoring_Eval, " + 
         " Project_Efficient, Project_Effective, Project_Sus_Nat_Own, " +
         " Project_QA_Summary, Project_Document_Status" +
      ") VALUES (" +
         "@pid, @ptitle, @date, @pqr, @pd, @ps, @pr, @pme, @pef, @pet, @psno, @pqs, @pds" + 
      ");" +
      " SET @result = @@rowcount; " +
      "INSERT INTO PC_QA_REPORT_2 (" + 
         " Project_M_Date, Project_M_Responsibility,Project_M_Notes" +
      ") VALUES(" + 
        " @pmd, @pmr, @pmn" +
      ");" + 
      " SELECT @result + @@rowcount; " +

      " COMMIT; ";

    //best to use a new connection object for each call to the database
    using (var con = new SqlConnection(" <connection string here> "))
    using (var cmd = new  SqlCommand(sql, con))
    {
        cmd.Parameters.Add("@pid", SqlDbType.Int).Value = int.Parse(pid);
        cmd.Parameters.Add("@ptitle", SqlDbType.NVarChar, 100).Value = ptitle;
        cmd.Parameters.Add("@date", SqlDbType.DateTime).Value = DateTime.Parse(date);
        cmd.Parameters.Add("@pqr", SqlDbType.Float).Value = double.Parse(pqr);
        cmd.Parameters.Add("@pd", SqlDbType.NVarChar, 5).Value = pd;
        //You can fill in the rest of the parameters on your own

        con.Open();
        return (int)cmd.ExecuteScalar();
     }
}

As a bonus, this will also fix the horrible sql injection vulnerability in the original code. 另外,这还将修复原始代码中可怕的 sql注入漏洞。

A. The unreachable code is because of 2 return statements. 答:无法到达的代码是因为有两个return语句。 A method can only return once. 一个方法只能返回一次。 Execution leaves the method after you return, hence any statements after it are unreachable code. 返回后,执行将离开该方法,因此该方法之后的所有语句均无法访问。

B. The way you are constructing your SQL commands is error prone and is open to SQL injections, please try using SQL parameters with a parametrized query instead. B.构造SQL命令的方式容易出错,并且易于进行SQL注入,请尝试将SQL参数与参数化查询一起使用。

Ex. 防爆。 ParameterizedQuery = Insert into Table1 values (@param1, @param2, @param3....) ParameterizedQuery =插入表1中的值(@ param1,@ param2,@ param3 ....)

C. Logically, this is a single insert - so you should think about doing in inside a DB transaction. C.从逻辑上讲,这是一个插入操作-因此,您应该考虑在DB事务内部进行操作。 If the first insert works and the second fails for some reason - you might end up with a bad state, depending on your actual data and requirements. 如果第一个插入有效,而第二个插入由于某种原因而失败-根据实际数据和要求,您可能会处于错误状态。

In regards to executing the two queries in one : 关于一次执行两个查询:

    SqlCommand cmd = new SqlCommand("INSERT INTO PC_QA_REPORT_1  (Project_ID, Project_Title, Date, Project_Quality_Rating, Project_Decision, Project_Strategic, Project_Relevant, Project_Monitoring_Eval, Project_Efficient, Project_Effective, Project_Sus_Nat_Own, Project_QA_Summary, Project_Document_Status) VALUES('" + pid + "','" + ptitle + "','" + date + "','" + pqr + "','" + pd + "','" + ps + "','" + pr + "','" + pme + "','" + pef + "','" + pet + "','" + psno + "','" + pqs + "','" + pds + "')", con);
    SqlCommand command = new SqlCommand("INSERT INTO PC_QA_REPORT_2 (Project_M_Date, Project_M_Responsibility,Project_M_Notes) VALUES('" + pmd + "','" + pmr + "','" + pmn + "')", con);

command += "; " + cmd;
int x = command.ExecuteNonQuery();
con.Close()
return x;

^ will work. ^将起作用。 As for the error you're getting... You can only return one thing from a function. 至于错误,您将得到...您只能从函数返回一件事。 You could, however, pass in integers as parameters ( by reference ) and modify them inside the function to get your return values 但是,您可以将整数作为参数传递(通过引用),并在函数内部进行修改以获取返回值

Since your query command doesn't accept a returned value, by use of executenonquery, you should be able to use one long string in your first cmd statement. 由于您的查询命令不接受返回值,因此通过使用executenonquery,您应该能够在第一个cmd语句中使用一个长字符串。 for example statement1; 例如statement1; statement2. 语句2。 Separate statement with semicolon. 用分号分隔语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM