string con = "Server=.;Database=project;user id=sa;pwd=12345";
string sql1 = "select ttimes from times where tday='2018-1-1'";
SqlConnection mycon = new SqlConnection(con);
mycon.Open();
SqlCommand sqlman = new SqlCommand(sql1, mycon);
string str1 = sql1;
int num1 = Convert.ToInt32(str1);
Console.WriteLine(num1);
这里的sql1的查询数值如何转换为整形num1
你需要调用sqlman
的ExecuteScalar()
方法,示例如下:
static public int AddProductCategory(string newName, string connString)
{
Int32 newProdID = 0;
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (@Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@Name", SqlDbType.VarChar);
cmd.Parameters["@name"].Value = newName;
try
{
conn.Open();
newProdID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return (int)newProdID;
}
更多C# + ADO.NET操作数据库的示例请参考:
ExecuteScalar返回第一行第一列的值,但是确保有记录才行,如果是统计日期2018-1-1这天的ttimes数据总和,应该用这个SQL语句
string sql1 = "select sum(ttimes) from times where tday='2018-1-1'";
object rst = sqlman.ExecuteScalar();//
int num1 = 0;
if (rst != null) num1 = (int)rst;//有记录值才转,要不null直接转报错