Create Oracle database and schema programmatically ADO.NET - c#

How can I create a oracle database programmatically in ADO.NET and a schema for it with userId + password so I can just go to my non-favorite tool the sql oracle developer tool where I just create a connection entering:
connectionstring name
UserId(schema)
password

I've done it with SQL before but never tried with ADO.NET ...
string connectionString = "...";
string oracleDataPath = "C:\\PATH_TO_ORADATA\\";
string username = "NEW_USER";
string password = "NEW_PWD";
string schema = "NEW_SCHEMA";
using (OracleConnection conn = new OracleConnection(connectionString))
{
conn.Open();
OracleCommand cmd = conn.CreateCommand();
cmd.CommandText = "CREATE TABLESPACE \"" + schema + "\" DATAFILE '" + oracleDataPath + schema + ".DBF' SIZE 10M AUTOEXTEND ON NEXT 1M";
cmd.ExecuteNonQuery();
cmd.CommandText = "CREATE USER \"" + username + "\" IDENTIFIED BY \"" + password + "\" DEFAULT TABLESPACE \"" + schema + "\" TEMPORARY TABLESPACE TEMP";
cmd.ExecuteNonQuery();
cmd.CommandText = "GRANT CONNECT TO \"" + username + "\"";
cmd.ExecuteNonQuery();
cmd.CommandText = "ALTER USER \"" + username + "\" QUOTA UNLIMITED ON \"" + schema + "\"";
cmd.ExecuteNonQuery();
}
Use the ADMIN/DBA account on the connection string.
Set oracleDataPath with the path where your Oracle keeps its data files.
Let me know if it works :-)

Related

MySQL SELECT INTO Variable, Getting 'Fatal Error encountered during command execution.'

I have tried MANY suggested solutions from here but nothing seems to work for this problem. I just keep getting this error message when it hits the 'mdr = command.ExecuteReader();' line. Any thoughts please?
try
{
MySqlConnection connection = new MySqlConnection("SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";");
MySqlCommand command;
MySqlDataReader mdr;
connection.Open();
string ThePID = tbPID.Text;
string TheRound = tbRound.Text;
string CurrentPage = tbCurrentPage.Text;
// SELECT #myvar:= myvalue
string query = "SELECT ImageURL, ProofingText " +
"INTO #ImageURL, #ProofingText " +
"FROM Rounds " +
"WHERE ProjectID = " + ThePID + " " +
"AND CurrentRound = " + TheRound + " " +
"AND Page = " + CurrentPage + ";";
command = new MySqlCommand(query, connection);
mdr = command.ExecuteReader();
mdr.Read();
rtProofing.Text = mdr.GetString("#PRoofingText");
tbURL.Text = mdr.GetString("#ImageURL");
tbImagePage.Text = Path.GetFileName(tbURL.Text);
PageBox.Image = Image.FromFile(tbURL.Text);
connection.Close();
connection.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
If you use MySqlConnector, you will get a helpful exception message that explains the problem:
Parameter '#ImageURL' must be defined. To use this as a variable, set 'Allow User Variables=true' in the connection string.
By default, MySQL queries (executed from .NET) can't use user-defined variables. You can relax this limitation by adding Allow User Variables=true to your connection string.
However, this won't fix your underlying problem, which is that this isn't the right way to select data from MySQL.
Firstly, your query is susceptible to SQL injection; you should rewrite it to use parameters as follows:
using (var command = connection.CreateCommand())
{
command.CommandText = #"SELECT ImageURL, ProofingText
FROM Rounds
WHERE ProjectID = #ThePID
AND CurrentRound = #TheRound
AND Page = #CurrentPage;";
commands.Parameters.AddWithValue("#ThePID", ThePID);
commands.Parameters.AddWithValue("#TheRound", TheRound);
commands.Parameters.AddWithValue("#CurrentPage", CurrentPage);
Then, you can retrieve the values with a slight variation on your current code. You must retrieve the values by their column names, which do not have a leading #. You should also check that a row was retrieved by examining the return value of Read():
if (mdr.Read())
{
rtProofing.Text = mdr.GetString("ProofingText");
tbURL.Text = mdr.GetString("ImageURL");
}
Finally, string concatenation is also not the right way to build a connection string. The MySqlConnectionStringBuilder class exists for this purpose; use it.
var builder = new MySqlConnectionStringBuilder
{
Server = server,
Database = database,
UserID = uid,
Password = password,
};
using var connection = new MySqlConnection(csb.ConnectionString);

C# MySQL Error: Keyword not supported

I have a problem with my writting to database and reading from database.
Here is my code:
MySqlConnection conn = new MySqlConnection(ConnectionString);
string ID = "";
MySqlCommand cmdRegister = new MySqlCommand("Insert into Players (username,password) values('"+"John"+"', '"+"johnisbest"+"')", conn);
cmdRegister.ExecuteNonQuery();
MySqlCommand cmdRead = new MySqlCommand("SELECT ID FROM Players WHERE username = '"+this.username+"';", conn);
MySqlDataReader reader = cmdRead.ExecuteReader();
conn.Open();
while (reader.Read())
{
ID = (string)reader["ID"];
}
conn.Dispose();
return ID;
It give me always error: Keyword not supported
Thanks for every help ;)
EDIT:
public MySQL(string IPaddress, string port, string username, string password, string database)
{
ConnectionString = "datasource=" + IPaddress + ";port=" + port + ";username=" + username + ";password=" + password + ";database=" + database + ";charse=utf_8";
}
sql = new MySQL("IP address to database", "3306", "username to database", "Here is my password to database", "name of my database");
ConnectionString = "datasource=" + IPaddress + ";port=" + port + ";username=" + username + ";pwd=" + password + ";database=" + database + ";charse=utf_8";
Tried to replace password with "pwd";
for me this work fine
Server=localhost;Database=testing;UID=root;password=testing;connect timeout=700;charset=utf8;pooling=true;Port=3306

OleDB Connection String to MySQL Connection String

I have this OleDB code which basically reads an excel file and displays it on to the datagridview after a button click:
string pathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtPath.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
OleDbConnection conn = new OleDbConnection(pathConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("SELECT * FROM [" + txtSheet.Text + "$]", conn);
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
dgvViewDrivers.DataSource = dt;
My question is that how would I make a MySQL Connection out of this OleDB connection string? Please help me.
You need to use MySQL .NET connector
http://dev.mysql.com/downloads/connector/net/
using (MySqlConnection conn = new MySqlConnection("SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";"))
{
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "sql here";
cmd.ExecuteNonQuery();
}
}
Your current code
This
using (vDBCon = new MySqlConnection("SERVER=localhost;Data Source=" + txtPath.Text + ";user=root;PASSWORD= ;"))
txtPath.Text needs to be the name of your database in MySQL. I assume you left the password out. If not you need one.
"SERVER=localhost;Data Source=MyDatabase;user=root;PASSWORD=MyPassword;"
where MyDatabase is the actual name of your database and MyPassword is the password you use to login with
You have to actually be running MySQL Server itself to create and connect to a MySQL database. it doesn't work of a file like Access. If you want something like that just use SQLite.
this
vCmd.CommandText = "SELECT * FROM [" + txtSheet.Text + "$]";
this you will be selecting data from your table in MySQL so it needs to look like
vCmd.CommandText = "SELECT * FROM MyTable";
where MyTable is actually the name of your table in the database

MySql Syntax error: You have an error in your SQL syntax near '' at line 1

EDIT: Apologies for the stupid question. My own lapse in concentration, plus the fact that I'm still just learning the SQL syntax kinda caused me to miss the issue.
Original Question: I have no clue as to what is going on here. I have tried several methods of inserting data, but none have worked so far, and I always get the same exception. I am uncertain what is causing the issue. Am I missing a command function or is there something wrong with the syntax?
string uName = "tess";
string uPwd = "newpassword";
int authorityLevel = 3;
try
{
mySqlCommand = mySqlConnect.CreateCommand();
mySqlCommand.CommandText = "INSERT INTO Users(UserName, UserPassword, AuthorityLevel) VALUES(\"" + uName + "\", \"" + uPwd + "\", " + authorityLevel + ";";
mySqlCommand.ExecuteNonQuery();
}
catch ((MySql.Data.MySqlClient.MySqlException e)
{
Console.WriteLine(e.Message);
}
// Output:
// 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 '' at line 1
You forgot a closing angular bracket ) at
mySqlCommand.CommandText = "INSERT INTO Users(UserName, UserPassword, AuthorityLevel) VALUES(\"" + uName + "\", \"" + uPwd + "\", " + authorityLevel + ";";
replace this with this
mySqlCommand.CommandText = "INSERT INTO Users(UserName, UserPassword, AuthorityLevel) VALUES(\"" + uName + "\", \"" + uPwd + "\", " + authorityLevel + ");";
And you added an extra opening angular bracket ( at
catch ((MySql.Data.MySqlClient.MySqlException e)
replace this with
catch (MySql.Data.MySqlClient.MySqlException e)
Use parameterized queries. It makes your code more readable and secure against sql injection attacks:
mySqlCommand.CommandText = "INSERT INTO Users(UserName, UserPassword, AuthorityLevel) VALUES(#name,#pw,#authorityLevel)";
mySqlCommand.Parameters.AddWithValue("#name", uName);
mySqlCommand.Parameters.AddWithValue("#pw", uPwd);
mySqlCommand.Parameters.AddWithValue("#authorityLevel", authorityLevel);
I Cant say anything about C# but your MySQL Insert syntax should like, If all columns are of string type
INSERT INTO Users(UserName, UserPassword, AuthorityLevel) VALUES('username','password','superadmin')
You are missing ) inyour query
mySqlCommand.CommandText = "INSERT INTO Users(UserName, UserPassword, AuthorityLevel) VALUES(\"" + uName + "\", \"" + uPwd + "\", " + authorityLevel + ");";
Use Parameterized Queries otherwise you will have SQL injection Attack
something Like this
String strQuery = "insert into customers (UserName, UserPassword, AuthorityLevel) VALUES(#name,#password,#authorityLevel)"
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#name", UserName);
cmd.Parameters.AddWithValue("#password", password);
Your Problem is simple: you are missing the ) at the end of your Query.
Try using this instead:
mySqlCommand.CommandText = "INSERT INTO Users(UserName, UserPassword, AuthorityLevel) VALUES('" + uName + "', '" + uPwd + "', '" + authorityLevel + "');";
Notice, that the last Parameter was also missing the quotes, and that I changed them to single-quotes.
Another Syntax-Error is at your catch-line:
catch ((MySql.Data.MySqlClient.MySqlException e)
You have two opening brackets - remove one of them.
Furthermore, you have to care about SQL-Injections. What, if the user enters this string to your name-field: username'; DROP DATABASE; --? Will it drop your database?
You should use string-escape-functions. Or - even better- use prepared Statement. Selman22's answer gives you an example on how to do that in C#.

access denied error while connecting to newly restored MDF database

I'm restoring a SQL Server .bak file on SQL Server Express. But after restoring the database, I cannot use it in my code, it seems that the file is somehow locked, and the only way is copying it to another folder, also when I try to copy the .mdf file (using Windows Explorer) I get a warning about admin permission. I cannot copy this file using C# File.Copy (unauthorizedaccessexception, access denied), here is my code:
SqlConnection myConn = new SqlConnection("Server=" + sqlname + ";Integrated security=SSPI;database=master");
string dbname = "tmpDB" + DateTime.Now.Ticks.ToString();
str = "CREATE DATABASE " + dbname + " ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = '" + System.IO.Path.GetDirectoryName(openDialogConvert.FileName) + "\\" + dbname + ".mdf') " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = '" + System.IO.Path.GetDirectoryName(openDialogConvert.FileName) + "\\" + dbname + ".ldf') ";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
myCommand.Dispose();
str = #"RESTORE DATABASE [" + dbname + "] FROM DISK = N'" + openDialogConvert.FileName + #"' WITH FILE = 1, MOVE N'IODB_Data'
TO N'" + System.IO.Path.GetDirectoryName(openDialogConvert.FileName) + "\\" + dbname + #".mdf', MOVE N'IODB_Log'
TO N'" + System.IO.Path.GetDirectoryName(openDialogConvert.FileName) + "\\" + dbname + #".ldf', REPLACE ";
myCommand = new SqlCommand(str, myConn);
myCommand.ExecuteNonQuery();
myCommand.Dispose();
myConn.Close();
//here I'm going to connect to my newly created & restored database, but I get access denied error
SqlConnection sql = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + System.IO.Path.GetDirectoryName(openDialogConvert.FileName) + #"\" + dbname + ".mdf ;Integrated Security=True");
sql.Open();
What is going wrong here? I want to connect to my newly restored database as soon as I restore my database.
I get following error when I try to connect to my newly created & restored .mdf:
Unable to open the physical file "D:\9 mordad fara\Ofogh-Dsk\Ofogh-Dsk\bin\Debug\tmpDB635110451805001328.mdf". Operating system error 5: "5(Access is denied.)".
An attempt to attach an auto-named database for file D:\9 mordad fara\Ofogh-Dsk\Ofogh-Dsk\bin\Debug\tmpDB635110451805001328.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
I suspect it may be already attached.
Can you connect using:
new SqlConnection("Server=" + sqlname +
";Integrated security=SSPI;" +
"database=" + dbname);

Categories