![](/img/trans.png)
[英]How to send JavaScript code to IE using C# (.Net 3.5), run it, then get a string return value from the JS code?
[英]How do I run SQL code using c# 3.5?
我有一個HTML文本框,其中包含一些需要執行的SQL代碼。 我可以從文本框中檢索實際的代碼,但是我不確定如何執行代碼。 使用c#3.5有任何簡單而優雅的方法嗎?
不要從文本框中執行代碼
除非您真的相信輸入的內容。
如果這樣做,請使用以下命令:
SqlConnection con = new SqlConnection("Your connection string");
con.Open();
SqlCommand cmd = new SqlCommand(TexdtBox1.Text, con);
cmd.ExecuteNonQuery();
con.Close()
注意,這不會返回任何內容,jsut運行查詢。 如果要返回數據,則需要SqlDataAdaptor或SqlDataReader。
這取決於您要對其執行數據庫的類型。 如果我可以假設您想與SQL Server數據庫進行對話,請查看以下類:
從文本框中使用CommandText創建SqlCommand 。
這是一些示例代碼(未經測試,未經測試,因為在SO文本框中鍵入了正確的代碼):
using System.Data;
namespace MyGreatNamespace
{
class MyGreatClass
{
static public DataTable executeTable( string query )
{
return executeTable( query, null, null );
}
static public DataTable executeTable( string query, string[] params, object[] values )
{
DataTable myTable = new DataTable();
using ( SqlConnection connection = new SqlConnection( myConnectionString ) )
using( SqlCommand command = new SqlCommand( connection ) )
{
command.CommandType = CommandType.Text;
command.CommandText = myQuery;
if ( parameters.Count == values.Count && parameters.Count > 0 )
{
for( int i = 0; i < parameters.Count; i ++ )
{
command.addParameterWithValue( parameters[i], values[i] );
}
}
using( SqlDataAdapter adapter = new SqlDataAdapter( command ) )
{
adapter.Fill( out myTable );
}
}
return myTable;
}
}
}
我不建議這樣做,但如果這樣做,至少要驗證輸入的SQL以SELECT開頭,並且不包含任何分號(;)或注釋字符(-和/ *)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.