ORA-00911: invalid character Error in C# Application - c#

I'm created app to connect Oracle Database XE 11g with ODAC 12, and take an error called "invalid character".
This is my ConnectionString:
connectionString="Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));User Id=hr;Password=12345;"
and code here
private void BtnConnect_OnClick(object sender, RoutedEventArgs e)
{
var sql = #"SELECT FIRST_NAME FROM EMPLOYEES
WHERE EMPLOYEE_ID = 120;";
var command = new OracleCommand(sql, Connection.Connect);
try
{
command.Connection.Open();
var reader = command.ExecuteScalar();
if (reader != null)
{
LblMessage.Content = "Connect Succeeded ";
LblMessage.Foreground = Brushes.Green;
}
else
{
LblMessage.Content = "Connect Failed";
LblMessage.Foreground = Brushes.Red;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
command.Connection.Close();
}
}
Somebody help me!

Standalone queries executed from your C# application shouldn't include the semicolon ; at the end. If you remove that, the ORA-00911 error should go away.

Related

Server version error while i am trying to connect to Heidisql

I must connect one database present in HeidiSql to my .Net project in visual studio. When i debug my project while i am doing connection with db i obtain the error in the field Server Version with the description '.server Version has generated an exception of type System.InvalidOperationException '. Do you know what is the reason?
My connection string is :
<connectionStrings>
<add name="TicketDB"
connectionString="server=localhost;user id=root;password=Omega;database=crm6"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
The code is:
public void getNumberAllTicketOpen()
{
try
{
clDataBase ticketDB = new clDataBase();
string sQuery = "SELECT * from ticket";
DataTable ticket = ticketDB.ExecuteDataTable(sQuery, null, false);
Console.WriteLine("i am here!");
}
catch (Exception e)
{
Console.WriteLine("Errore : " + e.Message);
}
finally
{
}
}
public DataTable ExecuteDataTable(string CommandText, List<SqlParameter> Params = null, bool isStoredProcedure = true)
{
SqlConnection oCnn = null;
SqlCommand oCmd = null;
SqlDataAdapter oAdap = null;
try
{
**oCnn = new SqlConnection(this.connectionString);
oCnn.Open();** //this is the line that launch the error
oCmd = new SqlCommand(CommandText, oCnn);
if (isStoredProcedure)
oCmd.CommandType = System.Data.CommandType.StoredProcedure;
else
oCmd.CommandType = System.Data.CommandType.Text;
oCmd.CommandTimeout = this.commandTimeOut;
if (Params != null)
{
foreach (SqlParameter p in Params)
oCmd.Parameters.Add(p);
}
oAdap = new SqlDataAdapter(oCmd);
DataTable ResultTable = new DataTable();
oAdap.Fill(ResultTable);
return ResultTable;
}
catch (Exception ex)
{
logger.Error("Errore esecuzione " + CommandText, ex, MethodInfo.GetCurrentMethod().Name + " in " + MethodInfo.GetCurrentMethod().Module.Assembly.FullName);
throw;
}
}
oCnn = new SqlConnection(this.connectionString);
oCnn.Open(); //this is the line with error
Thank you for your help!
The error you are showing is an error encountered by the Visual Studio debugger attempting to view a property of a SqlConnection object.
The property in question is ServerVersion. I'm guessing the connection would only know what version of MySQL is running on the server when it actually manages to connect to the server, but at the point you've stopped the code, it hasn't connected yet. It doesn't make sense to return the server version at that point, so throwing an InvalidOperationException is an appropriate response.
I see exceptions like this in the VS debugger quite often. They are nothing to worry about. Not every property on every object is valid all the time.
I have resolved my problem.
I was trying to connect to a mySQL database but there were error in my code. I have resolved with the installation of the package MySql.Data with NuGet and the replacement in the code of SqlConnection, SqlCommand, SqlDataAdapter respectively with MysqlConnection, MySqlCommand, MySqlDataAdapter. Below i write the modified code:
public DataTable ExecuteDataTable(string CommandText, List<MySqlParameter> Params = null, bool isStoredProcedure = true)
{
MySqlConnection oCnn = null;
MySqlCommand oCmd = null;
MySqlDataAdapter oAdap = null;
try
{
oCnn = new MySqlConnection(this.connectionString);
oCnn.Open();
oCmd = new MySqlCommand(CommandText, oCnn);
if (isStoredProcedure)
oCmd.CommandType = System.Data.CommandType.StoredProcedure;
else
oCmd.CommandType = System.Data.CommandType.Text;
oCmd.CommandTimeout = this.commandTimeOut;
if (Params != null)
{
foreach (MySqlParameter p in Params)
oCmd.Parameters.Add(p);
}
oAdap = new MySqlDataAdapter(oCmd);
DataTable ResultTable = new DataTable();
oAdap.Fill(ResultTable);
return ResultTable;
}
catch (Exception ex)
{
logger.Error("Errore esecuzione " + CommandText, ex, MethodInfo.GetCurrentMethod().Name + " in " + MethodInfo.GetCurrentMethod().Module.Assembly.FullName);
throw;
}
finally
{
if (oCnn != null)
{
if (oCnn.State != System.Data.ConnectionState.Closed)
oCnn.Close();
oCnn.Dispose();
}
if (oAdap != null)
oAdap.Dispose();
if (oCmd != null)
oCmd.Dispose();
if (Params != null)
{
Params.Clear();
Params = null;
}
}

update statement error in image

private void btnupdate_Click(object sender, EventArgs e)
{
byte[] img1 = File.ReadAllBytes(#"C:\Users\Admin\Desktop\Final Project Bridger\Bridger\Bridger\Images\20green.png");
try
{
if (txtfno.Text == "" && txtslab.Text == "")
{
MessageBox.Show("Update not possible");
}
else
{
cnn.Open();
cmd3.CommandText = "update Slab set indi = #img1 where s_flatno = #s_flatno and s_name = #s_name";
cmd3.Parameters.AddWithValue("#indi",img1);
cmd3.Parameters.AddWithValue("#s_flatno", txtfno.Text);
cmd3.Parameters.AddWithValue("#s_name", txtslab.Text);
cmd3.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
cnn.Close();
}
}
In this code, I'm updating image in the position indi and I'm setting a new img1 in byte. While press update I'm getting an error
Must declare scalar variable #img1
You have named your variable #img1 in the SQL Statement, but #indi when you declared the variable.
Please note that best practice when handling DBConnection is as a local variable inside a using statement, and you better use one of the overloads of Add when adding parameters to a command instead of AddWithValue. For more information, read Can we stop using AddWithValue() already?
Here is an improved version of your code:
private void btnupdate_Click(object sender, EventArgs e)
{
if (txtfno.Text == "" && txtslab.Text == "")
{
MessageBox.Show("Updation not possible");
}
else
{
try
{
byte[] img1 = File.ReadAllBytes(#"C:\Users\Admin\Desktop\Final Project Bridger\Bridger\Bridger\Images\20green.png");
var sql = "update Slab set indi=#indi where s_flatno=#s_flatno and s_name=#s_name";
// I'm assuming SQL Server based on the error message
using(var cnn = new SqlConnection(connectionString))
{
using(var cmd = new SqlCommand(sql, cnn))
{
cmd.Parameters.Add("#indi", SqlDbType.VarBinary).Value = img1;
cmd.Parameters.Add("#s_flatno", SqlDbType.VarChar).Value = txtfno.Text;
cmd.Parameters.Add("#s_name", SqlDbType.VarChar).Value = txtslab.Text;
}
cnn.Open();
cmd3.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
There is a small issue with you code. You have not passed #img1 parameter. You are sending it as #indi. Either Change #img1 to #indi in sql query string or change #indi to #img1 in add parameter statement:
cnn.Open();
cmd3.CommandText = "update Slab set indi=#indi where s_flatno=#s_flatno and s_name=#s_name";
cmd3.Parameters.AddWithValue("#indi",img1);
cmd3.Parameters.AddWithValue("#s_flatno", txtfno.Text);
cmd3.Parameters.AddWithValue("#s_name", txtslab.Text);
cmd3.ExecuteNonQuery();

C# Unable to detach database

I have a class that creates a database that saves the mdf file in a specified location. Then it copies tables from an existing database. Then creates stored procedures from an sql file. Then detaches the database created from the start once the process is done. My problem is that my detach method won't work throwing an exception saying that the database is in use. I have disposed my connections properly.
This is in-line with my previous question.
Here is my class:
Event
private void btnFullBackup_Click(object sender, EventArgs e)
{
progressBar.Value = 0;
lblStatus.Text = "Starting full backup...";
CreateDB("FULL");
progressBar.Value = 20;
lblStatus.Text = "Copying tables...";
CopyTables("FULL");
progressBar.Value = 60;
lblStatus.Text = "Creating stored procedures...";
CreateStoredProcedures("FULL");
progressBar.Value = 70;
progressBar.Value = 80;
DetachBackup("FULL");
lblStatus.Text = "Done";
progressBar.Value = 100;
MessageBox.Show("Backup was created successfully", "",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Methods used:
void CreateDB(string type)
{
//define and browse location to save mdf
lblStatus.Text = "Creating pysical database...";
FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
folderBrowserDialog.ShowDialog();
lblStatus.Text = "Checking folder permission...";
string selectedFolder = folderBrowserDialog.SelectedPath + "\\";
newBackupLocation = selectedFolder;
//check permission
if (WriteAccessToFolder(selectedFolder) == false)
{
MessageBox.Show("The folder you have chosen does not have write permission", "Monytron",
MessageBoxButtons.OK, MessageBoxIcon.Error);
folderBrowserDialog.ShowDialog();
return;
}
//create DB
lblStatus.Text = "Creating database...";
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var query = GetDbCreationQuery(selectedFolder, type);
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand(query, conn))
{
try
{
conn.Open();
command.ExecuteNonQuery();
folderBrowserDialog.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
if ((conn.State == ConnectionState.Open))
{
conn.Close();
}
}
}
}
void CopyTables(string backupDBName)
{
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var query = CopyQuery(backupDBName + DateTime.Now.ToString("yyyyMMdd"));
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand(query, conn))
{
try
{
conn.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
if ((conn.State == ConnectionState.Open))
{
conn.Close();
}
}
}
}
void CreateStoredProcedures(string type)
{
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (var conn = new SqlConnection(connectionString + ";database=" + type + DateTime.Now.ToString("yyyyMMdd")))
{
string spLocation = File.ReadAllText("CreateStoredProcedures.sql");
Server server = new Server(new ServerConnection(conn));
try
{
server.ConnectionContext.ExecuteNonQuery(spLocation);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
bool DetachBackup(string backupDBName)
{
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var builder = new SqlConnectionStringBuilder(connectionString);
string serverName = builder.DataSource;
string dbName = builder.InitialCatalog;
try
{
Server smoServer = new Server(serverName);
smoServer.DetachDatabase(backupDBName + DateTime.Now.ToString("yyyyMMdd"), false);
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
}
The Connection to the database is in most cases placed in a pool after using. This way you can re-connect quickly using the same connection string, but on the other hand, I suspect this pool of connections is blocking you from detaching a database.
You can probably do something like this:
Put use master as the last statement in each query against database before you close the connection, or
Modify connection string so it doesn't use pooling (uid=...; pwd=...; pooling=false;)
Hope it helps.
You should first kill connections to the database if you want to keep connection pooling. You can do it setting the database in single user access with rollback_immediate clause before calling the detach method.
Have a look here to use C#:
Is there a way to set the DB as Single User Mode in C#?
Or here to run T-SQL script:
https://serverfault.com/questions/76432/how-can-i-detach-a-database-that-is-in-use

The ConnectionString property has not been initialized using c# asp.net

Hi i am getting the following error while trying to update my database using c# asp.net.
Error:
Server Error in '/' Application.
The ConnectionString property has not been initialized.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The ConnectionString property has not been initialized.
Source Error:
Line 33: catch (Exception e)
Line 34: {
Line 35: throw e;
Line 36: }
Line 37: }
I am explaining my code below.
index.aspx.cs:
protected void reject_Click(object sender, EventArgs e)
{
//LinkButton lbtn = (LinkButton)(sender);
//lbtn.BackColor = System.Drawing.Color.Red;
GridViewRow grdrow = (GridViewRow)((LinkButton)sender).NamingContainer;
LinkButton lbtn = (LinkButton)grdrow.FindControl("accept");
LinkButton LRejectBtn = (LinkButton)grdrow.FindControl("reject");
// string status = grdrow.Cells[6].Text;
int healthId = int.Parse(lbtn.CommandArgument);
int result=0;
if (Convert.ToString(lbtn.BackColor) == "Color [Green]")
{
char updatedStatus = 'R';
result = objhealthCommentBL.updateStatusDetails(updatedStatus, healthId);
if (result == 1)
{
LRejectBtn.BackColor = System.Drawing.Color.Red;
lbtn.BackColor = System.Drawing.Color.WhiteSmoke;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Your status has updated successfully.')", true);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Your status couldnot updated')", true);
}
}
}
healthCommentBL.cs:
public int updateStatusDetails(char updatedStatus, int healthId)
{
int result;
try
{
result = objhealthCommentDL.updateStatusDetails(updatedStatus, healthId);
return result;
}
catch (Exception e)
{
throw e;
}
}
healthCommentDL.cs:
namespace DataAccess
{
public class healthCommentDL
{
SqlConnection con = new SqlConnection(CmVar.convar);
public DataSet getHealthCommentDetails()
{
try
{
con.Open();
DataSet ds = new DataSet();
string sql = "SELECT Health_Comment_ID,Health_ID,Health_Comment_Name,Health_comment_Email,Health_Comment_Message,Health_Comment_Website,Health_Comment_Status from T_Health_Comment";
sql += " order by Health_Comment_ID ASC ";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter objadp = new SqlDataAdapter(cmd);
objadp.Fill(ds);
return ds;
}
catch (Exception e)
{
throw e;
}
finally
{
con.Close();
con.Dispose();
}
}
public int updateStatusDetails(char updatedStatus, int healthId)
{
int result;
try
{
con.Open();
string query = "UPDATE T_Health_Comment SET Health_Comment_Status = #status WHERE Health_Comment_ID = #healthid";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#healthid", healthId);
cmd.Parameters.AddWithValue("#status", updatedStatus);
result = cmd.ExecuteNonQuery();
con.Close();
return result;
}
catch (Exception e)
{
throw e;
}
}
}
}
I am getting the above error in healthCommentBL.cs file in catch statement.Here i can say that the commentstring is properly working in the getHealthCommentDetails method in healthCommentDL.cs file but at the same time it is not working for the 2nd method of this file.Please help me to resolve this error.
When you write your connection as;
public class healthCommentDL
{
SqlConnection con = new SqlConnection(CmVar.convar);
It will be a field of healthCommentDL class, not a local variable. And it's properties (like ConnectionString) is not initialiazed. Instead of that, define your connections as a local variables in your methods. ADO.NET is pretty good at maintaining your connections as a local variables. Read: SQL Server Connection Pooling
public DataSet getHealthCommentDetails()
{
SqlConnection con = new SqlConnection(CmVar.convar);
and
public int updateStatusDetails(char updatedStatus, int healthId)
{
SqlConnection con = new SqlConnection(CmVar.convar);
A few things more;
You should always use parameterized sql. This kind of string concatenations are open for SQL Injection attacks.
Use using statement to dispose your connections and commands automatically instead of calling Close or Dispose methods manually.
Don't use AddWithValue method. It may generate unexpected and surprising results sometimes. Use Add method overloads to specify your parameter type and it's size.

C# Doesn't insert to mySQL database

I have some Steam trading bots and i am trying to insert to a database whether a trade was successful or not (true). You can see my code below. I get absolutely no errors and the regular trades, functions and console logging works fine. I check the db for content and nothing is there.
I am new to SQL in C#. Is someone able to tell me whats wrong with my code?
public override void OnTradeAccept()
{
bool didSomething = false;
if ((Validate()) || (IsAdmin && mode == ADMINMODE) || ChooseDonate)
{
bool success = Trade.AcceptTrade();
if (success) //makes sure trades were successfull
{
//I removed con details
string constr = "server=;database=;userid=;password=;";
MySqlConnection con = null;
try
{
con = new MySqlConnection(constr);
con.Open(); //open the connection
string insertTrue = "INSERT INTO trade_success(state) VALUES ('true')";
MySqlCommand command = new MySqlCommand(insertTrue, con);
command.ExecuteNonQuery();
}
catch (MySqlException err) //We will capture and display any MySql errors that will occur
{
Console.WriteLine("Error: " + err.ToString());
}
finally
{
if (con != null)
{
con.Close();
}
}
Log.Success("Trade was successful!");
//sendChatMessage(tradeSuccessMessage1);
sendChatMessage(tradeSuccessMessage2);
Bot.SteamFriends.SetPersonaState(EPersonaState.LookingToTrade);
}
else
{
Log.Warn("Trade might have failed.");
Bot.SteamFriends.SetPersonaState(EPersonaState.LookingToTrade);
}
}
}

Categories