![](/img/trans.png)
[英]How to retrieve data into a datagridview row by row from a SQL Server database using C#
[英]How to retrieve data from a SQL Server database in C#?
我有一個包含 3 列firstname
、 Lastname
和age
的數據庫表。 在我的 C# Windows 應用程序中,我有 3 個名為textbox1
的文本框......我使用以下代碼連接到我的 SQL Server:
SqlConnection con = new SqlConnection("Data Source = .;
Initial Catalog = domain;
Integrated Security = True");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tablename", con);
我想從我的數據庫中獲取值; 如果我在textbox1
中給出一個值,它必須匹配數據庫中的值並將其他詳細信息檢索到相應的文本框。
我嘗試了這種方法,但它不起作用:
cmd.CommandText = "select * from tablename where firstname = '" + textBox1.Text + "' ";
如何將所有其他值檢索到文本框?
public Person SomeMethod(string fName)
{
var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString();
Person matchingPerson = new Person();
using (SqlConnection myConnection = new SqlConnection(con))
{
string oString = "Select * from Employees where FirstName=@fName";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("@Fname", fName);
myConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
matchingPerson.firstName = oReader["FirstName"].ToString();
matchingPerson.lastName = oReader["LastName"].ToString();
}
myConnection.Close();
}
}
return matchingPerson;
}
這里有幾件事需要注意:我使用了參數化查詢,這使您的代碼更安全。 您使用"where x = "+ Textbox.Text +""
部分制作 select 語句的方式為您打開了 SQL 注入的大門。
我已將其更改為:
"Select * from Employees where FirstName=@fName"
oCmd.Parameters.AddWithValue("@fname", fName);
所以這段代碼要做的是:
對您的數據庫執行一條 SQL 語句,查看是否有與您提供的名字匹配的名字。 如果是這種情況,該人將被存儲在 Person 對象中(請參閱下面的類答案)。 如果沒有匹配,則 Person 對象的屬性將為null
。
顯然我不完全知道你在做什么,所以有幾點需要注意: 當有超過 1 個人的名字匹配時,只有最后一個會被保存並返回給你。 如果您希望能夠存儲這些數據,可以將它們添加到List<Person>
。
Person 類使其更清潔:
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
}
現在調用該方法:
Person x = SomeMethod("John");
然后,您可以使用來自 Person 對象的值填充文本框,如下所示:
txtLastName.Text = x.LastName;
創建一個名為 DbManager 的類:
Class DbManager
{
SqlConnection connection;
SqlCommand command;
public DbManager()
{
connection = new SqlConnection();
connection.ConnectionString = @"Data Source=. \SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True";
command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
} // constructor
public bool GetUsersData(ref string lastname, ref string firstname, ref string age)
{
bool returnvalue = false;
try
{
command.CommandText = "select * from TableName where firstname=@firstname and lastname=@lastname";
command.Parameters.Add("firstname",SqlDbType.VarChar).Value = firstname;
command.Parameters.Add("lastname",SqlDbType.VarChar).Value = lastname;
connection.Open();
SqlDataReader reader= command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
lastname = reader.GetString(1);
firstname = reader.GetString(2);
age = reader.GetString(3);
}
}
returnvalue = true;
}
catch
{ }
finally
{
connection.Close();
}
return returnvalue;
}
然后雙擊表單上的檢索按鈕(例如 btnretrieve)並插入以下代碼:
private void btnretrieve_Click(object sender, EventArgs e)
{
try
{
string lastname = null;
string firstname = null;
string age = null;
DbManager db = new DbManager();
bool status = db.GetUsersData(ref surname, ref firstname, ref age);
if (status)
{
txtlastname.Text = surname;
txtfirstname.Text = firstname;
txtAge.Text = age;
}
}
catch
{
}
}
從數據庫中檢索數據:
private SqlConnection Conn;
private void CreateConnection()
{
string ConnStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
Conn = new SqlConnection(ConnStr);
}
public DataTable getData()
{
CreateConnection();
string SqlString = "SELECT * FROM TableName WHERE SomeID = @SomeID;";
SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
DataTable dt = new DataTable();
try
{
Conn.Open();
sda.Fill(dt);
}
catch (SqlException se)
{
throw;
}
catch (Exception ex)
{
throw;
}
finally
{
Conn.Close();
}
return dt;
}
設置連接后,您可以使用這個簡單的方法:
private void getAgentInfo(string key)//"key" is your search paramter inside database
{
con.Open();
string sqlquery = "SELECT * FROM TableName WHERE firstname = @fName";
SqlCommand command = new SqlCommand(sqlquery, con);
SqlDataReader sReader;
command.Parameters.Clear();
command.Parameters.AddWithValue("@fName", key);
sReader = command.ExecuteReader();
while (sReader.Read())
{
textBoxLastName.Text = sReader["Lastname"].ToString(); //SqlDataReader
//["LastName"] the name of your column you want to retrieve from DB
textBoxAge.Text = sReader["age"].ToString();
//["age"] another column you want to retrieve
}
con.Close();
}
現在您可以通過 textBoxFirstName 將密鑰傳遞給此方法,例如:
getAgentInfo(textBoxFirstName.Text);
我們可以使用這種類型的代碼片段,我們通常也使用這種代碼來測試和驗證 DB 到 API 字段的數據
class Db
{
private readonly static string ConnectionString =
ConfigurationManager.ConnectionStrings
["DbConnectionString"].ConnectionString;
public static List<string> GetValuesFromDB(string LocationCode)
{
List<string> ValuesFromDB = new List<string>();
string LocationqueryString = "select BELocationCode,CityLocation,CityLocationDescription,CountryCode,CountryDescription " +
$"from [CustomerLocations] where LocationCode='{LocationCode}';";
using (SqlConnection Locationconnection =
new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(LocationqueryString, Locationconnection);
try
{
Locationconnection.Open();
SqlDataReader Locationreader = command.ExecuteReader();
while (Locationreader.Read())
{
for (int i = 0; i <= Locationreader.FieldCount - 1; i++)
{
ValuesFromDB.Add(Locationreader[i].ToString());
}
}
Locationreader.Close();
return ValuesFromDB;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
}
希望這可能會有所幫助
注意:你們需要連接字符串(在我們的例子中是“DbConnectionString”)
DataTable formerSlidesData = new DataTable();
DformerSlidesData = searchAndFilterService.SearchSlideById(ids[i]);
if (formerSlidesData.Rows.Count > 0)
{
DataRow rowa = formerSlidesData.Rows[0];
cabinet = Convert.ToInt32(rowa["cabinet"]);
box = Convert.ToInt32(rowa["box"]);
drawer = Convert.ToInt32(rowa["drawer"]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.