public void doTry()
{
db.ConnectionCheck();
string sqlUname = "";
string oracleUname = "";
string usertesting = "select * from nayatable";
db.cmd = new SqlCommand(usertesting, db.DBconnect);
SqlDataReader myReader = db.cmd.ExecuteReader();
if (myReader.Read())
{
sqlUname = myReader["USERNAME"].ToString();
//MessageBox.Show(uname);
textBox1.Text = sqlUname;
}
}
它只给出第一行第二个值,但我需要数据库中所有可用的列。
答案 0 :(得分:0)
这里有很多选项,您可以按照Ehsan的说法使用DataTable,也可以使用List来收集所有数据。像这样:
public class dbLogin
{
public string userName{get;set;}
}
public void doTry()
{
db.ConnectionCheck();
string sqlUname = "";
string oracleUname = "";
string usertesting = "select * from nayatable";
db.cmd = new SqlCommand(usertesting, db.DBconnect);
SqlDataReader myReader = db.cmd.ExecuteReader();
List<dbLogin> dbData=new List<dbLogin>();
if (myReader.Read())
{
dbLogin _dbLogin=new dbLogin();
_dbLogin.userName = myReader["USERNAME"].ToString();
textBox1.Text = sqlUname;
dbData.Add(_dbLogin);
}
}
答案 1 :(得分:0)
如果要获取所有值,则必须 loop :
...
// Keep Sql Readable
// Do not fetch unwanted columns - *
string userTesting =
@"select UserName
from NayaTable";
// Wrap IDisposable into using
using (db.cmd = new SqlCommand(userTesting, db.DBconnect)) {
// Wrap IDisposable into using
using(SqlDataReader myReader = db.cmd.ExecuteReader()) {
// we are going to build one string from many records
StringBuilder sb = new StringBuilder();
// Here, we have to loop and aggregate / collect all the records
while (myReader.Read()) {
if (sb.Length > 0)
sb.Append(", "); // delimiter
sb.Append(Convert.ToString(myReader["USERNAME"]));
}
// Here you'll get usernames like "Sam, John, Mary"
textBox1.Text = sb.ToString();
}
}