我初学编程和c#,照着一本书的例题在一个“项目”中添加了一个“数据库”,建立了一个数据“表”,并将这个数据库“添加新数据源”到我的“项目”中了。
这个数据“表”是这样的: 仓库编号 苹果数量 梨子数量 猕猴桃数量 香蕉数量 橙子数量
1 30 78 79 16 19
2 28 86 76 36 29
3 62 28 60 56 96
4 10 33 78 86 79
5 87 26 9 16 86 现在我想在程序中使用数据“表”中的某一个数据,比如说:仓库4中的猕猴桃数量,该用什么语句啊?请大侠们指教,谢谢先!
这个数据“表”是这样的: 仓库编号 苹果数量 梨子数量 猕猴桃数量 香蕉数量 橙子数量
1 30 78 79 16 19
2 28 86 76 36 29
3 62 28 60 56 96
4 10 33 78 86 79
5 87 26 9 16 86 现在我想在程序中使用数据“表”中的某一个数据,比如说:仓库4中的猕猴桃数量,该用什么语句啊?请大侠们指教,谢谢先!
string sql = @"select 猕猴桃数量 from 仓库库存 where 仓库编号 = 1"; sqlCommand cmd = new sqlCommand(sql, conn);
int k=(int)cmd.executescalar();
是这样吗?我这样在VS里有问题唉,是不是要加什么using ……啊?
sqlCommand cmd = new sqlCommand(sql, conn);
int k=(int)cmd.executescalar();
错误1 未能找到类型或命名空间名称“sqlCommand”(是否缺少 using 指令或程序集引用?)
错误3 当前上下文中不存在名称“conn”
sqlCommand cmd = new sqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
int k=(int)cmd.executescalar();
cs中
要加这个的,连接数据库用的
using System.Data
using System.Data.SqlClient
再用他们的说的那些话句试试
我加上“using System.Data.SqlClient”之后,有进展了,不过编译系统还是提示:错误3 当前上下文中不存在名称“conn”
using System.Data
using System.Data.SqlClient
public void DataTable GetData()
{
SqlConnection Con=new SqlConnection("你的链接字符串");
SqlCommand Com=new Sqlcommand(Con);
con.open();
Com.CommandText@"select 猕猴桃数量 from 仓库库存 where 仓库编号 = 1";
DataTable Ds=new DataTable();
SqlAdapter Da=new SqlAdapter(com);
Da.Fill(ds);
Com.executeNotQuery();
con.close();
return ds;
}
{}
可是我输入9楼的这第三句编译器就指出错误警告。9楼的意思肯定是到位了,可是对我来说理解他还需要一段历程,我对于其中哪个是自定义的名称,哪个是系统关键字都分不清。
using System.Data;
using System.Data.SqlClient; DataTable dt = SqlHelper.ExecuteDataset(this.ConnStr, CommandType.Text, "select 猕猴桃数量 from 仓库库存 where 仓库编号 = '1'").Tables[0]; 其中,ConnStr是数据库连接字符串
SqlConnection conn = new SqlConnection(source);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT 仓库编号,猕猴桃数量 FROM 表名";
conn.Open();
SqlDataReader reader= cmd.ExecuteReader(CommandBehavior.CloseConnection);
while(reader.read())
{
if(reader["仓库编号"]==4)
{
int num=(int)reader["猕猴桃数量"];
console.writeline("仓库4中的猕猴桃数量为{0}",num);
}
}
reader.close();
同学,你应该先学习下ADO。net