我正在尝试搜索数据库并在文本框中设置结果。我是 得到错误,表示“无效的强制转换异常”。我需要你的导游。
private void btn_search_Click(object sender, EventArgs e)
{
con.Open();
string STR="select * from TICKETSALES where REFERENCE="+txtSearch.Text;
cmd = new SqlCommand(STR,con );
dr = cmd.ExecuteReader();
if(dr.Read())
{
txtTrans.Text = dr.GetInt32("TRANSACTIONNUMBER").ToString();
txtPax.Text = dr.GetString("PASSENGERNAME");
}
else
{
MessageBox.Show("Ticket Number not Found");
}
}
答案 0 :(得分:1)
dr
以下是示例实现
con.Open();
//Use of camelCasing. transactionNumber instead of TRANSACTIONNUMBER
string STR="select transactionNumber,passengerNumber from TICKETSALES where REFERENCE=@search";
cmd = new SqlCommand(STR,con );
cmd.Parameters.Add("@search", txtSearch.Text);
dr = cmd.ExecuteReader();
if(dr.Read())
{
txtTrans.Text = Convert.ToString(dr[0]);
txtPax.Text = Convert.ToString(dr[1]);
}
最佳编码实践的一些提示(学分:@ tsahi-asher)
Paramere.Add()
函数将参数替换为其值select *
,使用特定的列名称。答案 1 :(得分:0)
这样的事情怎么样:
通过对sql查询进行参数化来注意sql注入保护。
private void btn_search_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
string query = "select top 1 TRANSACTIONNUMBER, PASSENGERNAME from ticketsales where reference=@ref";
using (SqlDataAdapter adap = new SqlDataAdapter(query, con))
{
con.Open();
DataTable dt = new DataTable();
adap.SelectCommand.Parameters.AddWithValue("@ref", txtSearch.Text.Trim());
adap.Fill(dt);
if (dt.Rows.Count > 0)
{
txtTrans.Text = dt.Rows[0]["TRANSACTIONNUMBER"].ToString().Trim();
txtPax.Text = dt.Rows[0]["PASSENGERNAME"].ToString().Trim();
}
else
{
MessageBox.Show("Ticket Number not Found");
}
}
}
}
答案 2 :(得分:0)
评论和帖子中已经提到的问题很少。我将填写我的评论 - 你没有处理非托管资源,一个答案涵盖了这一点,但它违反了你的代码。所以这是替代解决方案:
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
//some methods, fields
private void btn_search_Click(object sender, EventArgs e)
{
con.Open();
// as it has benn already said, you have to prevent yourself from SQL injection!
cmd = (new SqlCommand("select * from TICKETSALES where REFERENCE=@ref", con)).Parameters.AddWithValue("@res", txtSearch.Text.Trim());
dr = cmd.ExecuteReader();
if (dr.Read())
{
txtTrans.Text = dr.GetInt32("TRANSACTIONNUMBER").ToString();
txtPax.Text = dr.GetString("PASSENGERNAME");
}
else
{
MessageBox.Show("Ticket Number not Found");
}
}
// it looks like you have unamanaged resources held by fields in your form,
// so to release them you have to call their Dispose() method!
// normally you should use using keyword if they were used locally in a method, as other answer states
public void Dispose()
{
base.Dispose();
if (con != null) con.Dispose();
if (cmd != null) cmd.Dispose();
if (dr != null) dr.Dispose();
}