2017-12-07 10 views
-1

の後ろにC#コードでSQL Serverに適切に私はどのように、SQL Server Management Studioで

CREATE TABLE MyTable 
(
    EmployeeID int, 
    EmployeeDivision varchar(25), 
    EmployeeFName varchar(25), 
    EmployeeLName varchar(25), 
    EmployeeBudget1 int, 
    EmployeeBudget2 int, 
    EmployeeBudget3 int, 
    EmployeeBudget4 int, 
    EmployeeBudget5 int, 
    EmployeeBudget6 int, 
    EmployeeBudget7 int, 
    EmployeeBudget8 int, 
    EmployeeBudget9 int, 
    EmployeeBudget10 int, 
    EmployeeBudget11 int, 
    EmployeeBudget12 int, 
    EmployeeBudget13 int, 
    EmployeeBudget14 int, 
    EmployeeBudget15 int 
); 

INSERT INTO MyTable ('12345','DIVISION','FIRST','LAST','' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,''); 

私の質問は、どのように私はC#でこれを書くのですされている作成したクエリを引用符を挿入するには?

は、私が唯一のID、部門、姓、各従業員の姓の値を取得するテキストボックスの4セットを作成し、残りは予算1-15ここ

の場合はnullになります私のコードです:

SqlCommand cmd = new SqlCommand("insert into BUDGETTING_A values (' " + txtBoxEmpID.Text + "', + '" + cmbBoxDivision.Text + "','" + txtBoxFamilyName.Text + "', '" + txtBoxFirstName.Text + ' " + '','','','','','','','','','','','','','','"')"+, con); 

私はこれを行う上で問題がありますか?

+8

そのようなあなたのクエリを記述しないでください。 SQLインジェクションまであなた自身を開きます。 [parameters](https://stackoverflow.com/questions/10898737/parameterize-sql-query)を使用します。 – john

+0

最後の列に挿入しようとしているもの '、 '"') "+、con); ' –

+0

[Entity Framework]を使用してみてください(https://docs.microsoft.com/en-us/dotnet/framework/data/ adonet/ef/overview) –

答えて

0

あなたは、彼らが

INSERT INTO MyTable (EmployeeID ,EmployeeDivision ,EmployeeFName,EmployeeLName) 
values ('12345','DIVISION','FIRST','LAST') 

問い合わせの上、NULL可能である場合に値がそれらを指定いけない持っていけない場合は、単にあなただけの参照用です。 dbで正しく動作するようにクエリを記述してください。

1

最も安全で最良の方法は、次の例のようにSqlParameterを使用することです:

SqlCommand cmd = new SqlCommand("insert into BUDGETTING_A values (@BoxEmpID ,....) ",con); 
cmd.Parameters.AddWithValue("@BoxEmpID", txtBoxEmpID.Text); 
cmd.Parameters.AddWithValue("@OtherField", OtherValue); 
. 
. 
. 
cmd.ExecuteNonQuery(); 
関連する問題