Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

.net - How to create a .dbf file using c#?

I am trying this to make a select and it works just fine

string str = 
    "SELECT * FROM FREE RIGHT JOIN TestTest ON FREE.DOCNO = TestTest.DOCNO";
DataTable dt = new DataTable();
OdbcDataAdapter da = new OdbcDataAdapter(str, odbconn);
da.Fill(dt);

I am trying this to create a .dbf and i get this OdbcException :

string str0 = "Create Table Persons (Name char(50), City char(50), Phone char(20), Zip decimal(5))";
OdbcCommand cmd = new OdbcCommand(str0, odbconn);
cmd.ExecuteNonQuery();

ERROR [42000] [Microsoft][ODBC dBase Driver] Syntax error in field definition.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your problem is caused by Zip decimal(5), as the ODBC dBase driver doesn't like it. Off the top of my head, and after a quick google, I couldn't come up with a syntax it would tolerate. It does accept it quite merrily if you use the OleDb provider instead, as follows:

using (var dBaseConnection = new OleDbConnection(
    @"Provider=Microsoft.Jet.OLEDB.4.0; " +
    @" Data Source=C:UsersRobertWrayDocumentsdBase; " +
    @"Extended Properties=dBase IV"))
{
    dBaseConnection.Open();

    string createTableSyntax = 
        "Create Table Person " +
        "(Name char(50), City char(50), Phone char(20), Zip decimal(5))";
    var cmd = new OleDbCommand(createTableSyntax, dBaseConnection);
    cmd.ExecuteNonQuery();
}

One question though: Are you sure that you want to create the Zip column as a decimal? Not being a US resident I'm not 100% confident on this information, but, according to Wikipedia ZIP codes can start with a 0. Storing them as a numeric datatype won't allow you to accurately represent that.

My code for creating the table via ODBC:

using (var dBaseConnection = new OdbcConnection(@"Driver={Microsoft dBASE Driver (*.dbf)};DriverID=277;Dbq=C:UsersRobertWrayDocumentsdBase;"))
{
    dBaseConnection.Open();

    string str0 = "Create Table Person2 (Name char(50), City char(50), Phone char(20))";
    var cmd = new OdbcCommand(str0, dBaseConnection);
    cmd.ExecuteNonQuery();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...