public SqlConnection getcon()
{
//连接本地数据库 server=localhost
string M_str_sqlcon = @"server=localhost;database=表名;Integrated Security=SSPI";
SqlConnection myCon = new SqlConnection(M_str_sqlcon);
return myCon;
}
///
/// 创建一个DataTable对象
///
/// SQL语句
/// 表名
///
DataTable mytable = new DataTable();
public DataTable gettable(string M_str_sqlstr)
{
SqlConnection sqlcon = this.getcon();
SqlDataAdapter sqlda = new SqlDataAdapter(M_str_sqlstr, sqlcon);
sqlda.Fill(mytable);
sqlcon.Close();
sqlcon.Dispose();
return mytable;
}
调用该方法:
DataTable mytable = gettable("select * from 表名")
string test="";
string sql = "select class from table1 where name = '张三' ";
OleDbCommand cmd = new OleDbCommand(Sql, Connection);//第一个是SQL语句,Connection是链接字符串。当然你之前应该把它打开了。
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if(reader.Read())
{
test=reader["class"].ToString();
}
你可以测试下,备注我这里用的是ACCESS数据库的写法,如果你是SQL,自己改下就行。
把OleDb改成Sql的就可以了。
DataTable dtb = null;
string sql = "select class from table1 where name = '张三' ";
dtb = db.GetDataTable(db.form,sql);
string dtbStr=dtb.Rows[行下标][列下标].toString(); //两种写法,获得datatable中的某行某列的值
string dtbStr1=dtb.Rows[行下标]["列名"].toString();
dtb.Rows[0]["class"]就可以取出class的值了
using System.Data.SqlClient;
public SqlConnection con = new SqlConnection("Data Source=SUIBIAN\\SQLEXPRESS;Initial Catalog=MySchool_new;Integrated Security=True");