c#操作sql数据库,怎么在窗体中显示数据库中的一张表的所有记录,?

string str = "server=LENOVO007-PC\\SQLEXPRESS;database=脚本记录;user id=sa;pwd=sa";
SqlConnection con = new SqlConnection(str);
con.Open();
//进行查询
string sql = "selete * from 脚本记录";
SqlDataAdapter data = new SqlDataAdapter(sql, con);
//将查询结果作为临时表保存在数据集中
DataSet ds = new DataSet();
data.Fill(ds, "t");//*****
//显示数据
datagridview1.DataSource = ds.Tables["t"];
//上面是我按照书上写的,本来也不是很明白,到*****那里提示有错
数据库名称是脚本记录,表的名称也是脚本记录,这里不存在问题。。。

// 已修正,有错的地方下面都已给出:
string str = @"server=LENOVO007-PC\\SQLEXPRESS;database=脚本记录;user id=sa;pwd=sa";
            SqlConnection con = new SqlConnection(str);
            con.Open(); 
            //进行查询
            string sql = "SELECT * FROM 脚本记录"; // select你拼错了
            SqlDataAdapter data = new SqlDataAdapter(sql,con);
            DataSet ds = new DataSet();
            data.Fill(ds);
            con.Close() // 关闭连接
            dataGridView1.DataSource = ds.Tables[0];

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-03-01
可以调用griview控件进行数据绑定
第2个回答  2014-03-01
你这样改试试
data.Fill(ds,"脚本记录");
datagridview1.DataSource = ds.Tables["脚本记录"];

或者
data.Fill(ds);
datagridview1.DataSource = ds.Tables[0];追问

还是提示附近有语法错误。。。

追答

data.Fill(ds);
datagridview1.DataSource = ds.Tables[0];

追问

说了试过了不行,,,,

追答

你代码是写在一个方法中的?
public void Method()
{
//你的代码
}

估计楼主是一名新人 还有语法错误。。。

第3个回答  2015-08-13
1. ado.net提供了丰富的数据库操作,这些操作可以分为三个步骤:
第一,使用SqlConnection对象连接数据库;
第二,建立SqlCommand对象,负责SQL语句的执行和存储过程的调用;
第三,对SQL或存储过程执行后返回的“结果”进行操作。
2.连接字符串的写法string connectString = "Data Source=.;Initial Catalog=Student;Integrated Security=True";
3.返回数据库连接对象,参数字符串。实例化“连接对象”,并打开连接
SqlConnection sqlCnt = new SqlConnection(connectString);
sqlCnt.Open();
使用完成后,需要关闭“连接对象”
sqlCnt.Close();
4.实例化一个SqlCommand对象
SqlCommand command = new SqlCommand();
command.Connection = sqlCnt; // 绑定SqlConnection对象
5.执行SQLSqlCommand cmd = conn.CreateCommand(); //创建SqlCommand对象
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from products = @ID"; //sql语句
cmd.Parameters.Add("@ID", SqlDbType.Int);
cmd.Parameters["@ID"].Value = 1; //给参数sql语句的参数赋值
6.调用存储过程SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "存储过程名";
7.SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = System.Data.CommandType.TableDirect;
cmd.CommandText = "表名"
第4个回答  2014-03-01
用listview吧
相似回答