这是一个简单的例子,在窗体中托一个datagridView 控件,让它显示数据库中一张表的内容,通过dataset 实现。然后加一个按钮把更改后的信息保存到数据库。我的代码如下,可是出错。
请高人指点。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;namespace 同步到数据库
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }        SqlDataAdapter adapter = null;
        DataSet ds = new DataSet();        private void Form1_Load(object sender, EventArgs e)
        {
            string commandText = "select  号码 = psnNo,姓名 = psnName,性别 = psnSex,年龄 = psnAge from person2";
            SqlConnection cn = new SqlConnection("server =.\\sqlexpress;database=lht;Integrated Security = sspi");
            adapter = new SqlDataAdapter(commandText ,cn );            adapter.Fill(ds,"dtPerson");\\这一步报错,无法连接到数据库
            this.dataGridView1.DataSource = ds.Tables[0];
        }        private void button1_Click(object sender, EventArgs e)
        {
            SqlCommandBuilder sb = new SqlCommandBuilder(adapter);
            adapter.Update(ds.Tables [0]);
        }
    }
}

解决方案 »

  1.   

     // "uid=sa":连接数据库的用户名为sa.
                // "password=":连接数据库的验证密码为空.他的别名为"pwd",所以我们可以写为"pwd=".
                // "initial catalog=Northwind":使用的数据源为"Northwind"这个数据库.他的别名为"Database",本句可以写成"Database=Northwind".
                // "Server=YourSQLServer":使用名为"YourSQLServer"的服务器.他的别名为"Data Source","Address","Addr".
                // " Connect Timeout=30":连接超时时间为30秒.(根据情况添加)
                // PS:
                //  1.你的SQL Server必须已经设置了需要用户名和密码来登录,否则不能用这样的方式来登录.如果你的SQL Server设置为Windows登录,那么在这里就不需要使用"uid"和"password"这样的方式来登录,而需要使用"Trusted_Connection=SSPI"来进行登录.
                //  2. 如果使用的是本地数据库且定义了实例名,则可以写为"Server=(local)\实例名";如果是远程服务器,则将"(local)"替换为远程服务器的名称或IP地址.
                string strConnection = "Trusted_Connection=SSPI;";
                strConnection += "database=NTF_Navision_enlistment60;Server=CAIXIATA-6BE823;";
                strConnection += "Connect Timeout=30";
    本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/LCL_data/archive/2009/04/30/4139145.aspx
      

  2.   

    cn.Open();
                Console.WriteLine("ServerVersion: {0}", cn.ServerVersion);
                Console.WriteLine("State: {0}", cn.State);
                //查看连接的状态,如果状态不对,则是数据库的问题了
      

  3.   

    string commandText = "select  号码 = 'psnNo',姓名 = 'psnName',性别 = 'psnSex',年龄 = 'psnAge' from person2"; 是不是应该这样,SQL语句写错了,varchar类型的要加单引号('')
      

  4.   

    哈哈,知道了!其实一楼是正解,我的database 设置出了点问题。