How to add column to .DBF file? - c#

One of the issues I have is that, I don't think the table has a name... its just a .dbf file
So I've been trying this:
public void SQLAlter(string dbffile, string ColumnName )
{
//dbffile is "C:\MAPS\WASHINGTON\TLG_ROADS_L.DBF"
//ColumnName is "State"
if (File.Exists(dbffile))
{
System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection();
conn.ConnectionString = #"DSN=dBase Files";
conn.Open();
System.Data.Odbc.OdbcCommand comm = new System.Data.Odbc.OdbcCommand();
comm.CommandText = "ALTER TABLE " + dbffile + " ADD COLUMN " + ColumnName + " VARCHAR(1024)";
comm.ExecuteNonQuery();
}
}
The error is :
base {System.Data.Common.DbException} = {"ERROR [42S02]
[Microsoft][ODBC dBASE Driver] Cannot find table or constraint."}

I believe the table name is supposed to be the filename, and the connection string should point to the folder containing the dbf file.
var path = Path.GetDirectoryName(dbffile);
var tableName = Path.GetFileName(dbffile);
// ...
conn.ConnectionSTring = #"Driver={Microsoft dBASE Driver (*.dbf)};DriverID=277;Dbq=" + path;
comm.CommandText = "ALTER TABLE " + tableName + //...
Check connectionstrings.com: http://connectionstrings.com/dbf-foxpro

This is actually the correct syntax
comm.CommandText = "ALTER TABLE " + dbffile + " ADD COLUMN " + ColumnName + " VARCHAR(1024)";
However if your filename is longer than 8 characters it will not find it. Even though I tried it will an appropriate length file name, the "Operation [is] not supported on a table that contains data."
Various Internet links seem to indicate that one has to create a new table, and copy all the fields over.

Try another Provider.
It worked for me with the Visual Foxpro Provider
conn.ConnectionString = #"Provider=VFPOLEDB.1; Data Source=Themes.dbf" + #"\;Extended Properties=dBase IV";
If the driver is not installed on your machine, you get it here :
http://www.microsoft.com/en-us/download/details.aspx?id=14839

Related

"Syntax error in FROM clause" Excel in c#

i have an Excel file i want to raed it in c# using the OleDb like the following code:
string sheetName = "sheet1";
try
{
string stringConnection = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=excelfile.xls;Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;MAXSCANROWS=0';";
OleDbConnection OleDbConnection_ = new OleDbConnection(stringConnection);
OleDbCommand OleDbCommand_ = new OleDbCommand("select * from [" + sheetName + "$]; ", OleDbConnection_);
OleDbConnection_.Open();
DataTable DataTable_ = new DataTable();
DataTable_.Load(OleDbCommand_.ExecuteReader(), LoadOption.OverwriteChanges);
OleDbConnection_.Close();
}
catch (Exception)
{
throw;
}
Everything is working fine, just when i change the SheetName Value to " topos .architectures. bureaux " like the name in the xls file that i have, an exception was shown:
Syntax error in FROM clause.
what i messed it up here, thank you.
I think you just need to remove the $ in "select * from [" + sheetName + "$]; "
The $ is indeed use in references in Excel itself, but I think is does not apply to the OleDB command syntax
See this question for reference: Reading from excel using oledbcommand
The problem was in the dots in the Sheet name, the dots should be an #.
Like that:
"select * from ['" + sheetName.Replace('.', '#') + "$'];"

C#-sql update code. Too many columns in acess database

I have an c# program that update 2 columns, in each table in my access database file(.mdb). Columns that I'm updatnig are short string type, I am also changing their size to 255, before updating. I have 15 files, my code is working for first 7 dbs, and crash on 8-th file. I am updating each code separately, and it crash about in the middle of database
System.Data.OleDb.OleDbException: 'Record is too large.'
Query string that is crashing :
UPDATE CARTE SET SYMBOLE = 'AGLX19.A8E', SYMBOLE2 = 'AWLX19.A8E;#P516.#PQ;#P517.#PQ;#P518.#PQ;#P519.#PQ' WHERE CODE = '2862411';
private void UpdateSYMBOLEinDatabase(string tableName, string code)
{
if (symboleMdb[0] == "")
return;
string queryString = "UPDATE " + tableName +
" SET SYMBOLE = '" + symboleMdb[0] + "', SYMBOLE2 = '" + symboleMdb[1] + "' " +
"WHERE CODE = '" + code + "';";
if (symboleMdb[1] == "")
queryString = queryString.Replace(", SYMBOLE2 = ''", "");
using (OleDbConnection connectionInput = new OleDbConnection(connectionStringInput))
using (OleDbCommand command = new OleDbCommand(queryString, connectionInput))
{
connectionInput.Open();
command.ExecuteNonQuery();
command.Dispose();
}
}
I haved checked sql string carefully (also in online checker).
I had also search on google's and found that this error, is probably connected with too many columns in my db, actually when I am opening db file, there is about 220 columns. But when I am counting columns programmaticly it shows that there is about 878 columns(before/after changing length of short string type in columns). For others tables it shows correct count.
I found that copying table, may help. But actually I also can't do that.
private void CopyDeleteCopyDeleteQuery(string tableName)
{
string queryString = "CREATE TABLE " + tableName + "O"+
" AS (SELECT * FROM " + tableName +
" WHERE CODE='0801733');";
using (OleDbConnection connectionInput = new OleDbConnection(connectionStringInput))
using (OleDbCommand command = new OleDbCommand(queryString, connectionInput))
{
connectionInput.Open();
command.ExecuteNonQuery();
command.Dispose();
}
}
System.Data.OleDb.OleDbException: 'Syntax error in CREATE TABLE statement.'
Query string :
CREATE TABLE CARTEO AS (SELECT * FROM CARTE WHERE CODE='0801733');
The limit for fields is 2kB (excluding Memo and OLE. With ~220 columns fields, you are likely to be hitting that limit.
You should normalize the table, or convert some columns to Memo fields.

Error connecting to MS Access database from C# Winform

I'm a student programmer and I'm writing this software for a small school, it's my first program, the code below is giving me the error
syntax error in insert into statement
I know the connection string is not the problem because I use it for inserting into two other tables with the same insert into format.
I am using an access database.
The offending code is
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into studentBillRecords (StudentName, Department, Level, AccomodationStatus, SemesterBill, PreviousBalance, TotalBill) values ('"+ txtSRstudentName.Text + "', '" + cmbSRDepartment.Text + "', '" + cmbSRLevel.Text + "', '" + cmbSRAccomodationStatus.Text + "', '" + txtSRSemesterBill.Text + "', '" + txtSRPreviousBalance.Text + "', '" + txtSRTotalBill.Text + "')";
MessageBox.Show(command.CommandText);
command.ExecuteNonQuery();
connection.Close();
This same code with different table names, column names and input works with another table in the same database but won't work with this one.
Level is a reserved keyword in access.
Also use Parameters instead of concatinating string. Try this code out, it makes it safer and easier to read:
Note: I changed the name of the column Level to StudentLevel which, I assume, doesn't exist yet in your table.
try
{
using (OleDbConnection connection = new OleDbConnection("my connection string"))
{
//Open connection
connection.Open();
//Create new command
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
//Create command text
cmd.CommandText =
"INSERT INTO studentBillRecords " +
"(StudentName, Department, StudentLevel, AccomodationStatus, SemesterBill, PreviousBalance, TotalBill) VALUES " +
"(#StudentName, #Department, #StudentLevel, #AccomodationStatus, #SemesterBill, #PreviousBalance, #TotalBill)";
// Add names paremeters
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#StudentName", txtSRstudentName.Text),
new OleDbParameter("#Department", cmbSRDepartment.Text),
new OleDbParameter("#StudentLevel", cmbSRLevel.Text),
new OleDbParameter("#AccomodationStatus", cmbSRAccomodationStatus.Text),
new OleDbParameter("#SemesterBill", txtSRSemesterBill.Text),
new OleDbParameter("#PreviousBalance", txtSRPreviousBalance.Text),
new OleDbParameter("#TotalBill", txtSRTotalBill.Text)
});
//Execute Query
cmd.ExecuteNonQuery();
//No need to close because we are using "using"
}
}
catch (OleDbException ex)
{
//If an exception occurs let's print it out to console
Console.WriteLine("ERROR: " + ex.ToString());
throw;
}
For information on how to change the column name read this:
https://msdn.microsoft.com/en-us/library/bb177883(v=office.12).aspx
"Level" is a keyword in MS Access, may be that is why this issue occurs try quoting it like [Level]
List Of MS Access Keywords

C# and MySQL - Incorrect Syntax?

Suppose I this method from my MySQLOperations class:
public bool checkIfRowExists(string tableName, string columnToLookIn, string dataToLookFor)
{
string myConnectionString = "Server = " + server + "; Database = " + dbName + "; UID = " + user + "; Password = " + password + ";";
int isExisting = 0;
using (MySqlConnection myConnection = new MySqlConnection(myConnectionString))
{
using (MySqlCommand myCommand = new MySqlCommand("SELECT EXISTS (SELECT 1 FROM #tablename WHERE #columnname = #data);", myConnection))
{
myCommand.Parameters.AddWithValue("#tablename", tableName);
myCommand.Parameters.AddWithValue("#columnname", columnToLookIn);
myCommand.Parameters.AddWithValue("#data", dataToLookFor);
try
{
myConnection.Open();
isExisting = (int)myCommand.ExecuteScalar();
myConnection.Close();
}
catch (Exception ex)
{
myConnection.Close();
MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return (isExisting == 1);
}
}
}
And in another class, I created a MySQLOperations object.
I called on this method within an if statement: if(objSQLOperations.checkIfRowExists("tblInventory", "ItemID", txtItemID.Text)). Let us assume that txtItemID contains a valid 10-digit number. And that in my database, I have a table named tblInventory with a column ItemID.
My problem is that the statements within my catch block executes, saying there was an error with my SQL syntax. "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''tblInventory' WHERE 'ItemID' = '11111111111'' at line 1." is popped at a MessageBox when my txtItemID contains the text "1111111111".
I believe my SELECT EXISTS statement is correct.
No you can't use parameters for table or column names. You'll have to build up the SQL string dynamically by concatenation.
Like:
var sql = "SELECT EXISTS(SELECT 1 FROM " + tablename +
" WHERE " + columnNameToLookIn + " = #data);"
using (MySqlCommand myCommand = new MySqlCommand(sql, myConnection))
This of course opens you up to SQL injection if tableName and columnNameToLookIn can be user entered. However if the tableName and columnNameToLookIn are only set in code as it appears in your example then it is not a problem.
Related:
use a variable for table name in mysql sproc
Dynamic table names in stored procedure function

Wrong data type OleDB Create Table

I m using the following function to create an access table:
public static void createtable(string path, string tablename, string[] columnnames)
{
try
{
string connectionstring = creadteconnectionstring(path);
OleDbConnection myConnection = new OleDbConnection(connectionstring);
myConnection.Open();
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = myConnection;
string columnam = "[" + columnnames[0] + "] Text";
for (int i = 1; i < columnnames.Length; i++)
{
columnam = columnam + ", [" + columnnames[i] + "] Text";
}
myCommand.CommandText = "CREATE TABLE [" + tablename + "](" + columnam + ")";
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
Console.WriteLine("Access table " + tablename + " created.");
}
catch
{
Console.WriteLine("Access table " + tablename + " already exists.");
return;
}
}
However if I open the access table in MS access the data type is Memo, not Text. Other data types link specified by MS dont seem to work at all.
Any ideas are welcome? Thanks!
The Access DDL TEXT data type behaves differently depending on the context where you execute your statement.
From DAO in Access, this creates bar as a text field. But from ADO in Access, bar will be memo type.
CREATE TABLE tblFoo (bar TEXT)
Executing that statement from an OleDb connection produces the same result as with ADO in Access.
If you want bar to be an actual text field, include a field length <= 255.
CREATE TABLE tblFoo (bar TEXT(255))

Categories

Resources