[英]How to directly execute SQL query in C#?
好的,我有一個完全符合我需要的舊批處理文件。 但是,由於沒有進行新的管理,我們無法再運行批處理文件,因此我需要使用C#進行啟動。
我正在使用Visual Studio C#,並且已經為需要構建的應用程序設置了表單。 (我正在學習中)
這是我需要在C#中完成的工作(這是批處理膽量)
sqlcmd.exe -S .\PDATA_SQLEXPRESS -U sa -P 2BeChanged! -d PDATA_SQLEXPRESS -s ; -W -w 100 -Q "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday FROM [dbo].[TPatientRaw] WHERE tPatSName = '%name%' "
基本上,它使用SQLCMD.exe
和名為PDATA_SQLExpress
現有數據源。
我已經搜尋並接近了,但是從哪里開始我仍然茫然。
若要直接從C#中執行命令,可以使用SqlCommand類。
使用參數化的SQL(以避免注入攻擊)的快速示例代碼可能如下所示:
string queryString = "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday FROM [dbo].[TPatientRaw] WHERE tPatSName = @tPatSName";
string connectionString = "Server=.\PDATA_SQLEXPRESS;Database=;User Id=sa;Password=2BeChanged!;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("@tPatSName", "Your-Parm-Value");
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader["tPatCulIntPatIDPk"], reader["tPatSFirstname"]));// etc
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
這樣的事情就足以完成批處理文件的工作(將結果集以分號分隔的文本轉儲到控制台):
// sqlcmd.exe
// -S .\PDATA_SQLEXPRESS
// -U sa
// -P 2BeChanged!
// -d PDATA_SQLEXPRESS
// -s ; -W -w 100
// -Q "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday FROM [dbo].[TPatientRaw] WHERE tPatSName = '%name%' "
DataTable dt = new DataTable() ;
int rows_returned ;
const string credentials = @"Server=(localdb)\.\PDATA_SQLEXPRESS;Database=PDATA_SQLEXPRESS;User ID=sa;Password=2BeChanged!;" ;
const string sqlQuery = @"
select tPatCulIntPatIDPk ,
tPatSFirstname ,
tPatSName ,
tPatDBirthday
from dbo.TPatientRaw
where tPatSName = @patientSurname
" ;
using ( SqlConnection connection = new SqlConnection(credentials) )
using ( SqlCommand cmd = connection.CreateCommand() )
using ( SqlDataAdapter sda = new SqlDataAdapter( cmd ) )
{
cmd.CommandText = sqlQuery ;
cmd.CommandType = CommandType.Text ;
connection.Open() ;
rows_returned = sda.Fill(dt) ;
connection.Close() ;
}
if ( dt.Rows.Count == 0 )
{
// query returned no rows
}
else
{
//write semicolon-delimited header
string[] columnNames = dt.Columns
.Cast<DataColumn>()
.Select( c => c.ColumnName )
.ToArray()
;
string header = string.Join("," , columnNames) ;
Console.WriteLine(header) ;
// write each row
foreach ( DataRow dr in dt.Rows )
{
// get each rows columns as a string (casting null into the nil (empty) string
string[] values = new string[dt.Columns.Count];
for ( int i = 0 ; i < dt.Columns.Count ; ++i )
{
values[i] = ((string) dr[i]) ?? "" ; // we'll treat nulls as the nil string for the nonce
}
// construct the string to be dumped, quoting each value and doubling any embedded quotes.
string data = string.Join( ";" , values.Select( s => "\""+s.Replace("\"","\"\"")+"\"") ) ;
Console.WriteLine(values);
}
}
重要說明:除非完全信任用戶,否則不應連接SQL查詢。 查詢串聯涉及SQL注入被用來接管數據庫的風險。
如果您不想詳細介紹如何使用SqlCommand
執行查詢,則可以像下面這樣調用同一命令行:
string userInput = "Brian";
var process = new Process();
var startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = string.Format(@"sqlcmd.exe -S .\PDATA_SQLEXPRESS -U sa -P 2BeChanged! -d PDATA_SQLEXPRESS
-s ; -W -w 100 -Q "" SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName,
tPatDBirthday FROM [dbo].[TPatientRaw] WHERE tPatSName = '{0}' """, userInput);
process.StartInfo = startInfo;
process.Start();
只需確保您對每個雙引號"
和""
轉義即可
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.