C# C中SQL查询的正确语法
我目前正在使用asp.net webform从mssql中的数据库中提取数据。我有三个表tOptions,tModel,tOptions\u Model,数据字段是OptionsID,Options,ModelID,Model。表单所做的是,当您从dropdownlist中选择一个模型时,它将发送一个sql查询来获取与该模型对应的所有选项。我遇到的错误是,当您从dropdownlist中选择一个模型时,收到的错误如下: System.Data.dll中发生“System.Data.SqlClient.SqlException”类型的异常,但未在用户代码中处理 附加信息:“3”附近的语法不正确3表示在dropdownlist中选择的模型,因此它将是ddl中的第三项。我的问题是,这是基于所选模型获取所有选项的正确方法吗C# C中SQL查询的正确语法,c#,mysql,sql,sql-server,C#,Mysql,Sql,Sql Server,我目前正在使用asp.net webform从mssql中的数据库中提取数据。我有三个表tOptions,tModel,tOptions\u Model,数据字段是OptionsID,Options,ModelID,Model。表单所做的是,当您从dropdownlist中选择一个模型时,它将发送一个sql查询来获取与该模型对应的所有选项。我遇到的错误是,当您从dropdownlist中选择一个模型时,收到的错误如下: System.Data.dll中发生“System.Data.SqlClie
public partial class ModelsAndOptions : System.Web.UI.Page
{
private static System.Data.SqlClient.SqlConnection conn;
private static SqlDataSourceCommandEventArgs comm;
private static SqlDataReader reader;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
OpenConnection();
}
}
protected void ddlModel_SelectedIndexChanged(object sender, EventArgs e)
{
int optionsID;
string options;
ListItem optionsItem;
// clear the listbox just in case something is already inside it.
lbxOptions.Items.Clear();
string result = ("SELECT Options, OptionsID FROM tOptions WHERE ID = '('" + ddlModel.SelectedValue + "')'");
SqlCommand comm = new SqlCommand(result, conn);
try
{
reader.Close();
} catch (Exception ex)
{
}
//use reader obj to execute query
reader = comm.ExecuteReader();
// iterate through dataset by each line
while (reader.Read())
{
// stores primary key of options
optionsID = reader.GetInt32(0);
// stores name
options = reader.GetString(1);
// creates a list item with text of both the primary key and the name
optionsItem = new ListItem(options, optionsID.ToString());
// add items to the listbox
lbxOptions.Items.Add(optionsItem);
}
}
private void OpenConnection()
{
System.Configuration.ConnectionStringSettings strConn;
strConn = ReadConnectionString();
conn = new System.Data.SqlClient.SqlConnection(strConn.ConnectionString);
try
{
conn.Open();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
private System.Configuration.ConnectionStringSettings ReadConnectionString()
{
//string to store the path
String strPath;
strPath = HttpContext.Current.Request.ApplicationPath + "/Web.config";
//object that points to web.config file
System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(strPath);
System.Configuration.ConnectionStringSettings connString = null;
// if the connection string is working, then set the object to equal the connection string located inside the web.config file
if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
connString = rootWebConfig.ConnectionStrings.ConnectionStrings["kroegedlConnectionString"];
}
// return the connection string setting obj
return connString;
}
protected void btnAddOne_Click(object sender, EventArgs e)
{
lbxChosenOptions.Items.Add(lbxOptions.SelectedItem);
lbxOptions.Items.Remove(lbxOptions.SelectedItem);
}
}
犯了太多的罪
// Extract method: do not cram everything into single IndexChanged
private void CoreAddOptions() {
// Do not open a global connection
// Wrap IDisposable into using
using (SqlConnection conn = new SqlConnection(ConnectionString)) {
conn.Open();
// Make Sql Readable
// Make Sql paramterized
string sql =
@"select Options,
OptionsID
from tOptions
where Id = @prm_Id";
// Wrap IDisposable into using
using (SqlCommand comm = new SqlCommand(sql, conn)) {
// Do not hardcode SQL but use parameters
comm.Parameters.AddWithValue("@prm_Id", ddlModel.SelectedValue);
// Wrap IDisposable into using
using (var reader = comm.ExecuteReader()) {
while (reader.Read()) {
// Use Convert instead of Get + ToString
var optionsItem = new ListItem(
Convert.ToString(reader[0]),
Convert.ToString(reader[1]));
lbxOptions.Items.Add(optionsItem);
}
}
}
}
}
然后
创建一个存储过程并将经过验证的参数传递给它。 这降低了SQL注入的风险,并允许您更轻松地测试代码
将所有资源包装在using语句中,以确保它们已被释放。SQL注入警报!!!您的代码很容易受到sql注入攻击。在访问bobby tables之前,需要使用参数化查询。您的代码在这里也有许多其他问题。您没有正确处理连接和命令对象,这将杀死您的连接池。你也有我称之为try/squelch的东西,这是一个try-catch,但是catch没有任何作用。这是一种反模式,比不首先捕获错误更糟糕。对于手头的问题,您需要研究数据绑定。您不需要像这样循环遍历结果集并手动填充下拉框。解决查询问题的最佳方法是输出结果字符串,如果仅看到实际的查询字符串是不够的,则将其粘贴到Sql Server Management Studio中。您正在查询ID=3的位置,这是无效的语法;它是一个常量整数,介于两个单字符串之间,正好包含括号。
protected void ddlModel_SelectedIndexChanged(object sender, EventArgs e) {
CoreAddOptions();
}