C# to store data into MS-Access database - c#

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();
}
}

Related

idb2 connection not allowed with c#

i have a little problem with my connection with the AS400.I am using c#.
When i want to do an insert sql statement on a table, it pops this message
SystemInvalidOperationException : This operation cannot be successful
because the connection is not allowed at
IBM.Data.DB2.iSeries.iDB2Command.verifyConnection(); at
IBM.Data.DB2.iSeries.iDB2Command.ExecuteNonQuery();
here is my definition of the connection string
public static string userID;
public static string passwd;
public static string system;
public string query;
public iDB2Connection conn = new iDB2Connection("DataSource=" + system + ";UserID=" + userID + ";Password=" + passwd + ";DataCompression=true;");
and the code that contains the insert statement
public void insert(Programs prog, int nbfiche)
{
//conn.Open();
try
{
string sqlQuery = "INSERT INTO DIIAB.FICDET(MTPRO,MTFICH,MTPGM,MTNSRC,MTLSRC,MTTYP,MTOBJT) VALUES('" + Progiciel + "','" + nbfiche + "','" + prog.program_name +
"','" + prog.source_program + "','" + LIB + "','" + prog.element_type + "','" + prog.program_type + "')";
iDB2Command iDB2Command = conn.CreateCommand();
iDB2Command.CommandText = sqlQuery;
iDB2Command.ExecuteNonQuery();
sqlQuery = "select MTFICH from DIIAB.FICDET where MTFICH='" + nbfiche + "'";
iDB2Command command = conn.CreateCommand();
command.CommandText = sqlQuery;
iDB2DataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader[0].ToString().Contains(nbfiche.ToString()))
{
System.Windows.MessageBox.Show("Un programme à été rajouté à la fiche.");
}
}
System.Windows.MessageBox.Show("Les programmes ont été rajouté à la fiche", "Information");
}
catch (Exception e)
{
System.Windows.MessageBox.Show(e.ToString());
}
}
and the code that call the method insert with the parameters
edit.userID = userID;
edit.passwd = passwd;
edit.system = system;
edit editeur = new edit();
editeur.nbfiche = Convert.ToInt32(daoficnbr.fICNBR.nb_fiche);
editeur.fiche_status = Statuss.Text;
editeur.Progiciel = PRO.Text;
editeur.getpgm(arcad.lib,daoficnbr.fICNBR.nb_fiche);
foreach (Programs p in editeur.content)
{
editeur.insert(p, editeur.nbfiche);
}
Could help me please it's been already 2 days i am stuck on this one
Solution was to ensure that the connection string was terminated by a semi-colon and that the conn.Open() completed successfully before running commands or queries.

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();
}

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

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?

Backup SQL Server database by C# statement

I want to create a backup for the database I worked on my application by C# statement.
This is my code:
SqlConnection con = new SqlConnection(Connection.GetConnection());
SqlCommand command = new SqlCommand();
command.CommandText = "backup database [Pharmacy Database]to disk ="+"'"+path +"'";
command.CommandType = CommandType.Text;
command.Connection = con;
con.Open();
command.ExecuteNonQuery();
con.Close();
And gives me an error:
Cannot open backup device 'C:/Users/Abo Sala7/Desktop'.Operating system error 5 (failed to retrieve text for this error. Reason:15105).
BACKUP DATABASE is terminating abnormally.
Maybe the Problem is that your ServiceUser of the SQL-Service does not have the permission to write into the defined folder - The service is perfoming the backup - so this user must have the requiered permissions on the destination folder. (error 5 == Accessdenied)
I have been using the code below for back up, try this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
/// <summary>
/// Backups the data base.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <returns></returns>
public bool BackupDataBase(string fileName)
{
if (string.IsNullOrEmpty(fileName))
return false;
bool isDatabackedUp = true;
try
{
Backup sqlBackup = new Backup();
sqlBackup.Action = BackupActionType.Database;
sqlBackup.BackupSetDescription = "ArchiveDataBase:" +
DateTime.Now.ToShortDateString();
sqlBackup.BackupSetName = "Archive";
BackupDeviceItem deviceItem = new BackupDeviceItem(fileName, DeviceType.File);
ServerConnection connection = new ServerConnection(this.BackupConnection);
DataConnection dataConnection = new DataConnection();
Server sqlServer = new Server(dataConnection.ServerName);
Database db = sqlServer.Databases[dataConnection.DataBaseName];
sqlBackup.Database = dataConnection.DataBaseName;
sqlBackup.Initialize = true;
sqlBackup.Checksum = true;
sqlBackup.ContinueAfterError = true;
sqlBackup.Devices.Add(deviceItem);
sqlBackup.Incremental = false;
sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;
sqlBackup.FormatMedia = false;
sqlBackup.SqlBackup(sqlServer);
return isDatabackedUp;
}
catch (Exception)
{
return false;
}
}
private SqlConnection BackupConnection
{
get
{
string backupConnectionString = string.Empty;
ConnectionStringSettings settings =
ConfigurationManager.ConnectionStrings["LibrarySystemBackUpConnection"];
backupConnectionString = settings.ConnectionString;
SqlConnection backupDatabaseConnection = new SqlConnection(backupConnectionString);
return backupDatabaseConnection;
}
}
Here is a procedure is use for back up in C#.Hope it helps
public void BackupDatabase
(string BackUpLocation, string BackUpFileName, string DatabaseName, string ServerName )
{
DatabaseName = "[" + DatabaseName + "]";
string fileUNQ = DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() +"_"+ DateTime.Now.Hour.ToString()+ DateTime.Now .Minute .ToString () + "_" + DateTime .Now .Second .ToString () ;
BackUpFileName = BackUpFileName + fileUNQ + ".bak";
string SQLBackUp = #"BACKUP DATABASE " + DatabaseName + " TO DISK = N'" + BackUpLocation + #"\" + BackUpFileName + #"'";
string svr = "Server=" + ServerName + ";Database=master;Integrated Security=True";
SqlConnection cnBk = new SqlConnection(svr);
SqlCommand cmdBkUp = new SqlCommand(SQLBackUp, cnBk);
try
{
cnBk.Open();
cmdBkUp.ExecuteNonQuery();
Label1.Text = "Done";
Label2.Text = SQLBackUp + " ######## Server name " + ServerName + " Database " + DatabaseName + " successfully backed up to " + BackUpLocation + #"\" + BackUpFileName + "\n Back Up Date : " + DateTime.Now.ToString();
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
Label2.Text = SQLBackUp + " ######## Server name " + ServerName + " Database " + DatabaseName + " successfully backed up to " + BackUpLocation + #"\" + BackUpFileName + "\n Back Up Date : " + DateTime.Now.ToString();
}
finally
{
if (cnBk.State == ConnectionState.Open)
{
cnBk .Close();
}
}
}
internal void CreateDbBackup()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConStr"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = string.Format(#"BACKUP DATABASE [MyDatabase] TO DISK = N'{0}' WITH INIT , NOUNLOAD , NOSKIP , STATS = 10, NOFORMAT", UtilityClassGeneral.DbBackupPath);
con.Open();
cmd.ExecuteNonQuery();
}
}
internal void RestoreDbFromBackup()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConStr"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
con.Open();
// Make sure to get exclusive access to DB to avoid any errors
cmd.CommandText = "USE MASTER ALTER DATABASE [MyDatabase] SET SINGLE_USER With ROLLBACK IMMEDIATE";
cmd.ExecuteNonQuery();
cmd.CommandText = string.Format(#"RESTORE DATABASE [MyDatabase] FROM DISK = N'{0}' WITH FILE = 1, NOUNLOAD , STATS = 10, RECOVERY , REPLACE", UtilityClassGeneral.DbBackupPath);
cmd.ExecuteNonQuery();
}
}

Categories

Resources