C# 如何在C中从SQL Server数据库检索数据?
我有一个数据库表,有3列firstname、Lastname和age。在我的C Windows应用程序中,我有3个名为textbox1的文本框。。。我使用以下代码连接到我的SQL Server:C# 如何在C中从SQL Server数据库检索数据?,c#,sql,sql-server,C#,Sql,Sql Server,我有一个数据库表,有3列firstname、Lastname和age。在我的C Windows应用程序中,我有3个名为textbox1的文本框。。。我使用以下代码连接到我的SQL Server: SqlConnection con = new SqlConnection("Data Source = .; Initial Catalog = domain;
SqlConnection con = new SqlConnection("Data Source = .;
Initial Catalog = domain;
Integrated Security = True");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tablename", con);
我想从我的数据库中获取值;如果我在textbox1中给出一个值,它必须与数据库中的值相匹配,并将其他详细信息检索到相应的textbox
我尝试过这种方法,但不起作用:
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个人的名字匹配时,只有最后一个人会被保存并返回给你。
如果希望能够存储这些数据,可以将它们添加到列表中
使其更干净的人员类别:
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;
}
然后双击表单上的retrieve按钮.g 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)
{
DBErLog.DbServLog(se, se.ToString());
}
finally
{
Conn.Close();
}
return dt;
}
设置连接后,您可以使用以下简单方法: 现在,您可以通过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;
}
}
}
}
希望这会有帮助
注意:在我们的例子中,你们需要连接字符串
数据库连接字符串
你有名字、姓氏和年龄。域名是什么?为什么要计数*?为什么要在选择中进行计数*?一般来说,您永远不应该执行这种命令文本连接,因为您将面临sql注入的风险。。。设想一个用户输入';删除表tablename-@哈姆雷特·哈科比扬对不起,我更改了我的方便代码,因为我忘了更改它term@CSharper我想这是我提到的简单方法,我试过这个方法,但它不起作用,对你的问题根本没有帮助。这是一个很好的答案!确实是很好的回答。try-catch语句是唯一的东西missingAddWithValue@Fname,fName;F在查询中应该是小写/大写。Fname和Fname的参数名不应该相似吗?注意,SQLPerfor实例的参数名属性必须完全拼写为SQLSCOMPLE SQL命令字符串引用中使用的参数:可以考虑在类上添加IDISPOLIONE,然后使用AUTO进行自动清理。e、 g.usingDbManager db=newdbmanager{…}
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;
}
}
}
}
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"]);
}