问题描述
我无法从sql表中获取值并将其存储在变量中.
Hi, I''m having trouble getting a value from an sql table and storing it in a variable.
SqlConnection connection = new SqlConnection(ConnectionString.Conn);<br />
if (connection.State != ConnectionState.Open)<br />
{<br />
connection.Open();<br />
}<br />
<br />
SqlCommand command = connection.CreateCommand();<br />
command.CommandText = "SELECT * FROM LoginTable WHERE Username = ( ''" + username + "'')";<br />
SqlDataReader dataread = command.ExecuteReader();<br />
dataread.GetSqlInt32(cash);
LoginTable包含2个栏目:用户名和现金.
现金持有用户持有的现金量.我想要获取该值以便能够在我的应用程序中使用它,然后使用UPDATE作为sql命令将其更新回来.
但是,我的应用程序在
崩溃
LoginTable contains 2 coloums, Username and Cash.
Cash holds the amount of cash the user holds. I want to get that value to be able to use it in my application and then update it back using the UPDATE as an sql command.
However, my application crashes at
dataread.GetSqlInt32(cash);
错误状态:
没有数据时读取尝试无效.
而在名为的行中,整数值为1000.
非常感谢您的帮助.
Error states:
Invalid attempt to read when no data is present.
While in the row called there is an integer value of 1000.
Any help is greatly appreciated.
推荐答案
OleDbConnection dbConnection = new OleDbConnection();
OleDbCommand dbCommand = dbConnection.CreateCommand();
dbCommand.CommandType = CommandType.Text;
dbCommand.CommandText = "select * from tbl where user=''example''";
OleDbDataReader dbReader = dbCommand.ExecuteReader();
int cashValue = 0;
if (dbReader.HasRows)
{
while (dbReader.Read())
{
cashValue = Convert.ToInt32(dbReader["cash"]);
}
}
if (dataread.HasRows)
{
while (dataread.Read())
{
cashstring = (dataread.GetSqlValue(0).ToString());
}
}
dataread.Close();
cash = int.Parse(cashstring);
如fcronin所说进行了一些研究.这对我来说非常有效.谢谢=]
Did some research as fcronin said. This worked perfectly for me. Thank you =]
object objResult = dbCommand.ExecuteScalar();
int result;
if(objResult != null)
{
if(Int.TryParse(objResult,result out))
Console.Write("Result is: "+ result);
else
Console.Write("No data Found");
}
这篇关于从sql表中检索值并将其存储在变量中.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!