i wrote a form based C# program to read/write to a access data base. in it i have 2 tables: User and Item the following code should have read a spesific field from the User table and return it to me based on the field number but, i can't get it to work for some reason... help would be good at this point (4AM)
public string UserGetField(int user_id,int field)
{
string found="";
string command="";
switch (field)
{
case 1://first_name
command+= "first_name";
break;
case 2://last_name
command+= "last_name";
break;
case 3://grade
command+= "grade";
break;
case 4://phone
command+= "phone";
break;
case 5://address
command+= "address";
break;
case 6://item
command += "item";
break;
}
cmd.CommandText = "select '" + command + "' from User where user_id = '" + user_id + "'";
con.Open(); // open the connection
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
found += dr["first_name"].ToString();
}
con.Close();
return found;
}
try this:
cmd.CommandText = "select [" + command + "] from User where user_id = '" + user_id + "'";
Also, you're dynamically choosing the select field but always looking for the first_name field in the result. Change to
while (dr.Read())
{
found += dr[0].ToString(); // first field value
}
Try this ?
public string UserGetField(int user_id, int field)
{
var columns = new string[] { "first_name", "last_name", "grade", "phone", "address", "item" };
var list = new List<string>();
string command = columns[field - 1];
var sql = string.Format("select '{0}' from User where user_id = '{1}'", command, user_id);
var conStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Directory.GetCurrentDirectory() + @"\test.mdb"; //
using (var conn = new OleDbConnection(conStr))
{
conn.Open();
var cmd = new OleDbCommand(sql, conn);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
list.Add(dr[command].ToString());
}
}
return string.Join(",", list.ToArray());
}
this is the final version that works... swithced from table named User to Kids and made someother changes
public string UserGetField(int user_id,int field)
{
string found="";
string command="";
switch (field)
{
case 1://first_name
command+= "first_name";
break;
case 2://last_name
command+= "last_name";
break;
case 3://grade
command+= "grade";
break;
case 4://phone
command+= "phone";
break;
case 5://address
command+= "address";
break;
case 6://item
command += "item";
break;
}
cmd.CommandText = "SELECT " + command + " FROM Kids WHERE user_id = " + user_id + "";
con.Open(); // open the connection
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
found = dr[command].ToString();
}
con.Close();
return found;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.