在c#控制台应用程序中使用变量从数据库获取值
我有一个字符串作为c_编号。我想从我的数据库中获取数据,其中number是主键。它总是给出c_编号为无效列的错误。其中我的列名是number在c#控制台应用程序中使用变量从数据库获取值,c#,sql-server,C#,Sql Server,我有一个字符串作为c_编号。我想从我的数据库中获取数据,其中number是主键。它总是给出c_编号为无效列的错误。其中我的列名是number static void movies_on_rent() { SqlConnection con; SqlDataReader reader; try { Console.Clear(); con = new SqlConnection(Properties.Settings.Default.
static void movies_on_rent()
{
SqlConnection con;
SqlDataReader reader;
try
{
Console.Clear();
con = new SqlConnection(Properties.Settings.Default.connectionSQL);
con.Open();
Console.Write("Enter Customer phone :");
string c_number = Convert.ToString(Console.ReadLine());
reader = new SqlCommand("select * from customer_info where number=c_number", con).ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t\t\t{1} {2} {3}", reader.GetString(0), reader.GetInt32(1), reader.GetInt32(2), reader.GetString(3));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
确保您正在声明变量。此时未将C_编号指定给任何对象,并且由于缺少引号(最像您为列选择的数据类型),因此未将其标记为值 试着做下面的事情
string c_number = Console.ReadLine();
using (SQLConnection con = new SQLConnection(Properties.Settings.Default.connectionSQL))
{
SQLCommand Command = new SQLCommand("Select * from customer_info where number=@cnumber", con);
Command.Parameters.AddWithValue("@c_number", c_number);
SQLDataReader Reader = Command.ExecuteReader();
// Now use the data reader
}
此外,当“IDisposable”接口可用时,始终建议使用“using”语句 在该命令文本中,字符串c_number只不过是一个文本字符串,而不是要用于查询数据库的变量的名称。你应该学习如何编写参数化查询你能告诉我如何解决它吗…?关于堆栈溢出,互联网上有无数的问题和教程。去花30秒研究这个。