照书上把程序抄下来竟有错!!!
using System;
using System.Data;
using System.Data.SqlClient;class MyClass
{ public static void Main() 
{
//数据库连接
SqlConnection conPubs = new SqlConnection  ("server=localhost;uid=sa;pwd=;database=pubs");
conPubs.Open();
    
                  SqlDataAdapter dbAdapter = new SqlDataAdapter("select au_id,au_lname,au_fname,contract from authors",conPubs);
SqlCommandBuilder sqlBuilder = new SqlCommandBuilder(dbAdapter);
DataSet dbset = new DataSet();
dbAdapter.Fill(dbset,"authors");
    Console.WriteLine("修改前的记录数:{0}",dbset.Tables["authors"].Rows.Count); //增加行
DataRow newRow = dbset.Tables["authors"].NewRow();
newRow["au_id"] = "1111-1111-1111";
newRow["au_lname"] = "blek";
newRow["au_fname"] = "Snow";
newRow["contract"] = 1;
dbset.Tables["authors"].Rows.Add(newRow);

//添加到数据库中
try
{
dbAdapter.Update(dbset,"authors");
}
catch(Exception e)
{
Console.WriteLine("Exception occur!");
Console.WriteLine("Exception:{0}",e);
}
Console.WriteLine("修改后的记录数:{0}",dbset.Tables["authros"].Rows.Count);
conPubs.Close();

}
}现在提示有三处错误!!!
1.Console.WriteLine("修改前的记录数:{0}",dbset.Tables["authors"].Rows.Count);
2.Console.WriteLine("修改后的记录数:{0}",dbset.Tables["authros"].Rows.Count);
3.dbAdapter.Update(dbset,"authors");
还有:SqlCommandBuilder的作用是什么啊?不知道前两句为什么错?第三个问题可能是自己把这些对象没搞清楚吧?
帮帮吧,谢谢了!!!

解决方案 »

  1.   

    我试着运行了一下,只有一个错误,是因为newRow["au_id"] = "1111-1111-1111";
    newRow["au_lname"] = "blek";
    newRow["au_fname"] = "Snow";这里有有一个字段长度>数据库里的定义的长度了。
    你说的那几个都没错。
      

  2.   

    2.Console.WriteLine("修改后的记录数:{0}",dbset.Tables["authros"].Rows.Count);
    这是运行到这一行出现的错误:
    未处理的“System.NullReferenceException”类型的异常出现在 ConsoleApplication1.exe 中。3.dbAdapter.Update(dbset,"authors");
    运行这一行抛出的异常为:
    Exception occur!
    Exception:System.Data.SqlClient.SqlException: 将截断字符串或二进制数据。
       at System.Data.Common.DbDataAdapter.Update(DataRow[] dataRows, DataTableMapping tableMapping)
       at System.Data.Common.DbDataAdapter.Update(DataSet dataSet, String srcTable)
       at MyClass.Main()
      

  3.   

    3.dbAdapter.Update(dbset,"authors");Exception:System.Data.SqlClient.SqlException: 将截断字符串或二进制数据。这个就是数据库字段的长度不够引发的错误
      

  4.   

    现在将上边的auid值改为:
    newRow["au_id"] = "998-72-3568";
    其输出结果为:
    修改前的记录数:23
    未处理的异常: System.NullReferenceException: 未将对象引用设置到对象的实例。
       at MyClass.Main()
    但我把
    2.Console.WriteLine("修改后的记录数:{0}",dbset.Tables["authros"].Rows.Count);这一句加注释后,输出为:
    修改前的记录数:23
    又没有异常抛出,是什么原因啊?
      

  5.   

    解决了,太大意了!"authros"应该为authors