How i can delete database from local server without database files - c#

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

Related

How to upload a DB backup to a FTP server

On the tail end of database backup project and I've run into a issue where the Deflate compression I put in can't seem to find the path I saved the backup to. Being that the default backup location (used here) is on a network drive is there something else I need to do to make sure the path is found by Deflate? As of now I get System.IO.DirectoryNotFoundException: 'Could not find a part of the path. The purpose of the tool is to be able to put in any server you want to access, get a list of available DB's and then choose the one you want to backup.
I had this issue before locally, but all i had to do was give SQLserver the proper permissions to the folder.
using (SqlConnection newConn = new SqlConnection(connString))
using (SqlCommand sqlCmd = new SqlCommand(query, newConn))
{
newConn.Open();
value = sqlCmd.ExecuteScalar();
canCompress = !(value == null || Convert.ToInt32(value) == 0);
//----------------------------------
//SQL Commands to run backup process
//----------------------------------
Interface.WriteLine("Creating backup");
if (canCompress)
{
sqlCmd.CommandText = "BACKUP DATABASE [" + connBuilder.InitialCatalog + "] "
+ "TO DISK = '" + backupFile + "' "
+ "WITH COPY_ONLY, COMPRESSION, NOFORMAT, NOINIT, "
+ "NAME = '" + backupName + "', "
+ "SKIP, REWIND, NOUNLOAD, STATS = 10";
sqlCmd.ExecuteNonQuery();
}
else
{
sqlCmd.CommandText = "BACKUP DATABASE [" + connBuilder.InitialCatalog + "] "
+ "TO DISK = '" + backupFile + "' "
+ "WITH COPY_ONLY, NOFORMAT, NOINIT, "
+ "NAME = '" + backupName + "', "
+ "SKIP, REWIND, NOUNLOAD, STATS = 10";
sqlCmd.ExecuteNonQuery();
}
//----------------------------------
//Grab Backup File
//----------------------------------
query = "SELECT physical_device_name "
+ "FROM msdb.dbo.backupset b "
+ "JOIN msdb.dbo.backupmediafamily m ON b.media_set_id = m.media_set_id "
+ "WHERE database_name = '" + connBuilder.InitialCatalog + "' "
+ "ORDER BY backup_finish_date DESC ";
using (SqlConnection connection = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(query, connection))
{
connection.Open();
value = cmd.ExecuteScalar();
if (value != null)
backupFile = (string)value;
else
throw new Exception("Unable to find backup file.");
}
//Set which files should be uploaded.
if (canCompress)
{
fileToUpload = backupFile;
}
else
{
fileToUpload = Deflate.CompressFile(backupFile); //Point of error message
File.Delete(backupFile);
}
return fileToUpload;
}
static class Deflate
{
public static string CompressFile(string sourcePath, string destPath = null)
{
if (destPath == null)
destPath = Path.Combine(Path.GetDirectoryName(sourcePath), Path.GetFileNameWithoutExtension(sourcePath) + ".cmp");
using (FileStream originalFileStream = File.OpenRead(sourcePath))
using (FileStream compressedFileStream = File.Create(destPath))
using (DeflateStream compressionStream = new
DeflateStream(compressedFileStream, CompressionMode.Compress))
{
originalFileStream.CopyTo(compressionStream);
compressedFileStream.Flush();
}
FileInfo sourceInfo = new FileInfo(sourcePath); //Remove the .bak extension on compression?
FileInfo destInfo = new FileInfo(destPath); //Remove the .bak extension on compression?
Console.WriteLine("Compressed {0} from {1} to {2} bytes.", Path.GetFileName(sourcePath), sourcePath.Length, destInfo.Length);
return destPath;
}
}

C# - Syntax error in INSERT INTO statement (An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll)

System.Data.OleDb.OleDbCommandBuilder cb; //command builder
cb = new System.Data.OleDb.OleDbCommandBuilder(boosterbaseDa); //re-establish temporary connection
DataRow dRow = boosterbaseDs.Tables[drpCardSet.Text].NewRow(); //create new row in set
dRow[0] = drpCardSet.Text + "-EN" + txtCardSetNo.Text; //grab the data
dRow[1] = txtCardName.Text;
dRow[2] = drpCardRarity.Text;
dRow[3] = drpCardCatagory.Text;
dRow[4] = updCardInStock.Value;
MessageBox.Show(dRow[0] + ", " + dRow[1] + ", " + dRow[2] + ", " + dRow[3] + ", " + dRow[4]);
boosterbaseDs.Tables[drpCardSet.Text].Rows.Add(dRow); //add row
boosterbaseMaxRows = boosterbaseMaxRows + 1;
string cardTable = drpCardSet.Text;
boosterbaseDa.Update(boosterbaseDs, drpCardSet.Text);
I seem to be getting stuck on the last line, with an error of
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll, Syntax error in INSERT INTO statement
I realize there are similar questions but I am seriously stuck with this.
The table does exist and I can make a connection to the database.
Examples of the data going in (into the table "LOB") would be LOB-EN001, Bob, Common, Monster, 1.
Thank you in advance - Sam
This worked as one solution.
string connetionString = null;
OleDbConnection connection;
OleDbDataAdapter oledbAdapter = new OleDbDataAdapter();
string sql = null;
connetionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source=../boosterbase.mdb";
connection = new OleDbConnection(connetionString);
sql = "insert into " + drpCardSet.Text + " values('" + drpCardSet.Text + "-EN" + txtCardSetNo.Text + "','" + txtCardName.Text + "','" + drpCardRarity.Text + "', '" + drpCardCatagory.Text + "', '" + updCardInStock.Text + "')";
try
{
connection.Open();
oledbAdapter.InsertCommand = new OleDbCommand(sql, connection);
oledbAdapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Row(s) Inserted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
From http://csharp.net-informations.com/dataadapter/insertcommand-oledb.htm
Via Update requires a valid InsertCommand when passed DataRow collection with new rows

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 to create mdf database file dynamicly using C# code by optional "Recovery model" option?

I have created C# code which creates a .mdf SQL Server database file and this code works just fine.
There only few options are missing.
Especially I need to choose
either database "Recovery model" is full mode or simple mode and
either "Auto shrink" value is true or false during during creation of a database!
Code:
private void buttonCreateData_Click(object sender, EventArgs e)
{
String CreateDatabase;
SqlConnection connection = new SqlConnection("Server=(localdb)\\Projects;Integrated security=SSPI;database=master");
CreateDatabase = "CREATE DATABASE " + textBoxDataName.Text + " " +
"ON PRIMARY " +
"(NAME = '" + textBoxDataName.Text + "', " +
"FILENAME = '" + Directory.GetCurrentDirectory() + "\\" + textBoxDataName.Text + ".mdf', " +
"SIZE = 6MB, MAXSIZE = 4GB, FILEGROWTH = 10%) " +
"LOG ON " +
"(NAME = '" + textBoxDataName.Text + "_LOG" + "', " +
"FILENAME = '" + Directory.GetCurrentDirectory() + "\\" + textBoxDataName.Text + ".ldf', " +
"SIZE = 1MB, MAXSIZE = 200MB, FILEGROWTH = 10%)" +
"";
SqlCommand command = new SqlCommand(CreateDatabase, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("Database is created successfully", "Database", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "Database", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
}
Remember I don't need to create the database firstly and then modify those two options. I need to set those two options during creation of database.
So what should I add in that code, I mean what kind of statement is missing in order to choose those two options during real-time?

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?

Categories

Resources