C#如何执行一个字符串,然后存储该结果?
仅供参考,此页面(add.ashx.cs)是数据库的添加页面。C#如何执行一个字符串,然后存储该结果?
我试图做的是:
- 弄清楚如何执行字符串queryID和queryID
的那么
// new query to get last ID value
// store the command.executeNonQuery results into a variable
string queryID = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
// first: look up how to execute queryID
// then: store results of query^
// execute queryID? (section below)
SqlConnection sqlConnection1 = new SqlConnection(queryID);
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "Select * FROM queryID";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// data is accessible through the datareader object here
sqlConnection1.Close();
在您的代码示例中有一些内容不匹配。第一个queryID
是您的实际查询。其次,在SqlConnection
中,您需要提供一个连接字符串,它连接到您的数据库(SQL Server,ACCESS,...)。一个有效的例子可能是这样的:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
SqlConnection sqlConnection1 = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(sqlConnection1);
SqlDataReader reader;
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
List<string> results = new List<string>();
if(reader.HasRows)
{
while(reader.Read())
{
results.Add(reader[0].ToString());
}
}
sqlConnection1.Close();
另一件事是,你执行一个阅读器,但只选择一个单一的值。您可以完美地使用ExecuteScalar
:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
SqlConnection sqlConnection1 = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(sqlConnection1);
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
string result = cmd.ExecuteScalar().ToString();
sqlConnection1.Close();
最后一件事。您应该在使用块中使用实现IDisposable
的对象。这种方式将在不再需要时从内存中移除:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
using(SqlConnection sqlConnection1 = new SqlConnection(connectionStr))
{
SqlCommand cmd = new SqlCommand(sqlConnection1);
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
string result = cmd.ExecuteScalar().ToString();
}
期望的内容while这个答案是正确的,这个代码需要一些改进。 1.查询本身可以简化为'SELECT IDENT_CURRENT('dbo.license_info')'2.在using语句中使用所有的IDisposable实例 - SqlConnection,SqlCommand和SqlDataReader都实现了IDisposable。 –
@ZoharPeled你是对的,我仍然在编辑我的答案与改进(但我错过了SQL改进) –
我upvoted它无论如何:-) –
您正试图连接到其连接字符串为某个SQL的数据库。如果你想执行'queryID',那么你应该把它放在'CommandText'中(并且将实际的连接字符串传递给'SqlConnection'而不是'QueryID') – litelite
请阅读关于SqlConnection的文档以及构造函数 –