Import some csv column data into SQL Server 2008 R2 (programmatically) - c#

I'd like to insert CSV data into a SQL Server database at one time. I know about BULK INSERT but I need to select some fields only. So I try INSERT INTO like below -
try
{
OleDbConnection myOleDbConnection = new OleDbConnection("Provider=SQLOLEDB;Data Source=ServerName;Integrated Security=SSPI;Initial Catalog=DBName;User ID=sa;Password=password");
myOleDbConnection.Open();
string strSQL = null;
strSQL = "INSERT INTO " + strTable + "(" + M_ItemCode + "," + M_ItemDesc + "," + M_UOM + ") " + "SELECT " + M_ItemCode + "," + M_ItemDesc + "," + M_UOM + " FROM [Text;DATABASE=E:\temp\\Item.csv]" ;
OleDbCommand cmd = new OleDbCommand(strSQL, myOleDbConnection);
return (cmd.ExecuteNonQuery() == 1);
}
catch (Exception ex)
{
Common.ShowMSGBox(ex.Message, Common.gCompanyTitle, Common.iconError);
return false;
}
I got the error
Invalid object name 'Text;DATABASE=E:\temp\Item.csv'.
Is my syntax wrong?

Related

Postgresql Npgsql.PostgresException in c#

I have a problem with cmd.ExecuteReader() i get a Npgsql.PostgresException
public void connectDB()
{
try
{
server = "localhost";
database = "DoveVer3";
uid = "admin";
password = "admin";
string connectionString;
connectionString = "Host=" + server + ";Username =" + uid + ";" + "PASSWORD=" + password + ";DATABASE=" + database;
connection.ConnectionString = connectionString;
connection.Open();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
I get the Exeption in the code below:
public void AddDoveToDB(Dove dove)
{
//add new dove record to tableDB
connectDB();
cmd = new NpgsqlCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT * FROM " + DoveTableDB + " WHERE `" + DoveIdColumnDoveTable + "` = '" + dove.GetDoveId() + "'";
NpgsqlDataReader rdr = cmd.ExecuteReader(); //// <<<<< HERE
if (rdr.Read() != true)
{
rdr.Close();
cmd.Parameters.Clear();
cmd.CommandText = "INSERT INTO " + DoveTableDB + "(" + DoveIdColumnDoveTable + "," + DoveIdFatherColumnDoveTable + "," + DoveIdMotherColumnDoveTable + "," + DoveEyesColorColumnDoveTable + "," + DoveFeatherColorDoveTable + "," + DoveImageNameColumnDoveTable + "," + DoveSexColumnDoveTable +") VALUES ('" + dove.GetDoveId() + "','" + dove.GetDoveFatherId() + "','" + dove.GetDoveMotherId() + "','" + dove.GetEyesColor() + "','" + dove.GetFeathersColor()+ "','" + dove.GetImageName() + "','" + dove.GetSex()+ "')";
cmd.ExecuteNonQuery();
}
connection.Close();
}
My database is called DoveVer3 and my schema DoveSchema here is my table code:
Name: DoveTable; Type: TABLE; Schema: DoveSchema; Owner: admin
--
CREATE TABLE "DoveTable" (
"doveId" character varying(20)[] NOT NULL,
"doveFather" character varying(20)[],
"doveMother" character varying,
"doveEyesColor" character varying(20)[],
"doveFeathersColor" character varying(20)[],
"doveSex" smallint DEFAULT 3 NOT NULL,
"imageName" character varying(30)
);
ALTER TABLE "DoveTable" OWNER TO admin;
The Exceptions Base messege:
relation "dovetable" don't exist; Statemants: {SELECT * FROM DoveTable
WHERE doveId = 'Test'}
By default all identifiers passed to PostgreSQL will be considered lower-case. Based on your creation script you used a quoted-identifer when defining your table so the following is required when using the name of your table.
SELECT * FROM "DoveTable"
Notice that it is wrapped in double quotes and the 'D' and 'T' are both capitalized. When using quoted-identifiers you must always write them out exactly the way you defined them.

ORA:00933 SQL Command Not Properly Ended Error, while syncing Oracle and SQL Databases through C#.Net Application

I'm trying to update a table from Oracle Database to a table in SQL Server. But I'm getting an error:
ORA-00933 SQL COMMAND NOT PROPERLY ENDED.
I've tried every way to deal with it but not getting any solution.
static void Main(string[] args)
{
OleDbConnection conOracle = new OleDbConnection(connectionString);
conOracle.Open();
SqlConnection conSql = new SqlConnection(conStr);
conSql.Open();
//data set for Updation in CwsFaultyOracleSqlSYN Table in SQL
DataSet dsCWS = new DataSet();
string strUPDCWS = "SELECT SERIALNUMBER, GROUPCODE, PARTNO, RECCHALLANNO, RECDATE, FROMBRANCH, ";
strUPDCWS += " RECHUB, DEFSRNO, OKSRNO, FCRNO, FCRDATE, RECDTYPE, SEQNUMBER ";
strUPDCWS += " FROM CwsFaultyOracleSqlSYN WHERE INSFLG='N' ";
OleDbCommand cmdUPDCWS = new OleDbCommand(strUPDCWS, conOracle);
OleDbDataAdapter adpUPDCWS = new OleDbDataAdapter();
adpUPDCWS.SelectCommand = cmdUPDCWS;
adpUPDCWS.Fill(dsCWS, "table1");
//DataSet dsSqlUPDCWS = new DataSet();
string strSQLUPDCWS = "";
string OLEupdCWS = "";
if (dsCWS.Tables[0].Rows.Count > 0)
{
foreach (DataRow i in dsCWS.Tables[0].Rows)
{
try
{
strSQLUPDCWS = "UPDATE CwsFaultyOracleSqlSYN SET GROUPCODE='" + i["GROUPCODE"].ToString().Trim() + "', PARTNO='" + i["PARTNO"].ToString().Trim() + "',";
strSQLUPDCWS += " RECCHALLANNO='" + i["RECCHALLANNO"].ToString().Trim() + "',RECDATE='" + i["RECDATE"].ToString().Trim() + "',FROMBRANCH='" + i["FROMBRANCH"].ToString().Trim() + "',RECHUB='" + i["RECHUB"].ToString().Trim() + "',";
strSQLUPDCWS += " DEFSRNO='" + i["DEFSRNO"].ToString().Trim() + "',OKSRNO='" + i["OKSRNO"].ToString().Trim() + "',FCRNO='" + i["FCRNO"].ToString().Trim() + "',FCRDATE='" + i["FCRDATE"].ToString().Trim() + "',RECDTYPE='" + i["RECDTYPE"].ToString().Trim() + "',SERIALNUMBER='" + i["SERIALNUMBER"].ToString().Trim() + "'";
strSQLUPDCWS += " WHERE SEQNUMBER='" + i["SEQNUMBER"].ToString().Trim() + "'";
SqlCommand cmdUPDSqlCWS = new SqlCommand(strSQLUPDCWS, conSql);
cmdUPDSqlCWS.ExecuteNonQuery();
//Updating Flag in Oracle Database
OLEupdCWS = "UPDATE CwsFaultyOracleSqlSYN SET INSFLG='Y' AND INSDATE = SYSDATE WHERE SEQNUMBER='" + i["SEQNUMBER"].ToString().Trim() + "'";
OleDbCommand cmdOraceUpd = new OleDbCommand(OLEupdCWS, conOracle);
cmdOraceUpd.ExecuteNonQuery();
}
}
}
}
Well, I think this row:
OLEupdCWS = "UPDATE CwsFaultyOracleSqlSYN SET INSFLG='Y' AND INSDATE = SYSDATE WHERE SEQNUMBER='" + i["SEQNUMBER"].ToString().Trim() + "'";
Should be this:
OLEupdCWS = "UPDATE CwsFaultyOracleSqlSYN SET INSFLG='Y' WHERE SEQNUMBER='" + i["SEQNUMBER"].ToString().Trim() + "' AND INSDATE = SYSDATE ";
Note: your AND was before the WHERE.
Also, as mentioned in the comments, you really should use parameters when dealing with databases, unless you want a visit from little bobby tables.

How i can delete database from local server without database files

If database files .mdf and .log do not exist in folder with application then i need to create new database, but if i do like this
CREATE DATABASE Mydvds.mdf
And i have exception that databese Mydvds.mdf is alredy exist. If i try to drop database like this
DROP DATABASE Mydvds.mdf
I have exception that base is not exist or i don't have premmisions.
I was checking database list by way of
SELECT * FROM sysdatabases
And C:\Mydvds.mdf in this list.
How i can remove this database from server?
Or can you tell me about another way do this?
public void create_db()
{
string base_path = Environment.CurrentDirectory + #"..\..\..\My_cool_db.mdf";
string log_path = Environment.CurrentDirectory + #"..\..\..\My_cool_db_log.ldf";
string ConnectionString = #"Data Source=(LocalDB)\v11.0";
string cmnd_create_db;
connection = new SqlConnection(ConnectionString);
cmnd_create_db = "CREATE DATABASE My_cool_db ON PRIMARY " +
"(NAME = My_cool_db, " +
"FILENAME = '" + #base_path + "', " +
"SIZE = 4MB, MAXSIZE = 20MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = My_cool_db_log, " +
"FILENAME = '" + #log_path + "', " +
"SIZE = 4MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + #base_path + ";Integrated Security=True";
connection = new SqlConnection(ConnectionString);
cmnd = connection.CreateCommand();
cmnd.CommandText = cmnd_create_db;
connection.Open();
cmnd.ExecuteNonQuery();
List<string> db_cmnd = new List<string>();
db_cmnd.Add(File.ReadAllText(Environment.CurrentDirectory + "\\res\\Main.sql"));
db_cmnd.Add(File.ReadAllText(Environment.CurrentDirectory + "\\res\\Category_table.sql"));
db_cmnd.Add(File.ReadAllText(Environment.CurrentDirectory + "\\res\\ForeignKeyConstraint1.sql"));
foreach (string command_text in db_cmnd)
{
cmnd.CommandText = command_text;
cmnd.ExecuteNonQuery();
}
connection.Close();
connection.Dispose();
cmnd.Dispose();
}

C# to store data into MS-Access database

I need to write C# code to insert data into an MS-Access database. The program adds it but if I close the application the database resets.
database is in the debug x86 folder
Here is my code for adding data
provider = "Provider=Microsoft.ACE.OLEDB.12.0";
applicatiePad = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("\\"));
pad = "Data Source=" + applicatiePad + "/Geluidsfragmentendb.accdb";
connectionString = provider + ";" + pad;
connection = new OleDbConnection(connectionString);
...
public bool VoegToe(int geluidsfragmentnr,
string Titel,
string bestandsnaam,
int min,
int sec)
{
string time = min + ":" + sec;
DateTime tijd = Convert.ToDateTime(time);
String voegGfToe = "INSERT INTO Geluidsfragment (GeluidsfragmentID, Titel, bestandsnaam, tijdsduur) VALUES (" + geluidsfragmentnr + ",'" + Titel + "'" + ",'"+ bestandsnaam + "','" + tijd + "')";
OleDbCommand command = new OleDbCommand(voegGfToe, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
return true;
}
catch ( Exception e)
{
MessageBox.Show(e.Message);
return false;
}
finally
{
connection.Close();
}
}

Syntax Error on a Sql Parametrized update command - c#

It's my first SQL Parametrized update command in c# and i have a syntax error when i exectued my update.
Here is my code :
string maRequete = "UPDATE " + strNomTable + " set "
+ "evetype = #evetype ,"
+ "evedes = #evedes ,"
+ "evecli = #evecli ,"
+ "eveusermo = #eveusermo ,"
+ "eveinterv = #eveinterv where eveNum = " + '"' + strEvtNumeroString.ToString() + '"';
OleDbCommand DbCommand = new OleDbCommand(maRequete);
DbCommand.Parameters.Add("#evetype", OleDbType.VarChar);
DbCommand.Parameters.Add("#evedes", OleDbType.VarChar);
DbCommand.Parameters.Add("#evecli", OleDbType.VarChar);
DbCommand.Parameters.Add("#eveusermo", OleDbType.VarChar);
DbCommand.Parameters.Add("#eveinterv", OleDbType.VarChar);
DbCommand.Parameters["#evetype"].Value = m_strEvtType.ToString().Trim();
DbCommand.Parameters["#evedes"].Value = m_strDesignation.ToString().Trim();
DbCommand.Parameters["#evecli"].Value = m_strCodeClient.ToString().Trim();
DbCommand.Parameters["#eveusermo"].Value = m_strUserModification;
DbCommand.Parameters["#eveinterv"].Value = m_strCodeIntervenant.ToString().Trim();
try
{
string strStringConnect = #"Provider=vfpoledb.1;Data Source=" + m_strDirectoryDBF + "\\" + strDbfFile + ".dbf;Collating Sequence=general";
OleDbConnection DbConnection = new OleDbConnection(strStringConnect);
DbCommand.CommandType = System.Data.CommandType.Text;
DbConnection.Open();
DbCommand.Connection = DbConnection;
DbCommand.ExecuteNonQuery();
return "O";
}
catch (Exception Ex)
{
return Ex.Message;
}
Anyone have an idea where is my mistake ? In addition, i wrote in a old DBF file (Visual Foxpro) and i think i don't have access to log in order to debug the query :(.
Thanks a lot :)
Best regards,
Nixeus
Try using single quotes in your UPDATE statement instead of double quotes. The last line
+ "eveinterv = #eveinterv where eveNum = " + '"' + strEvtNumeroString.ToString() + '"';
should be
+ "eveinterv = #eveinterv where eveNum = '" + strEvtNumeroString.ToString() + "'";
change your command text as
string maRequete = "UPDATE " + strNomTable + " set "
+ "evetype = #evetype ,"
+ "evedes = #evedes ,"
+ "evecli = #evecli ,"
+ "eveusermo = #eveusermo ,"
+ "eveinterv = #eveinterv where eveNum = '" + strEvtNumeroString.ToString() + "'";
If you print out maRequete, and try executing it interactively, you will find the SQL syntax is incorrect. It seems likely you're using double-quotes to denote string constants; in SQL you should use single quotes for that. It's possible your data contains a single quote (i.e. an apostrophe). In that case, you need to add and extra one e.g.
INSERT ... values ('you''ll need two apostrophes for this');
These are just SQL rules. You have to give the server valid syntax if it's to execute your query.

Categories

Resources