C# MySql.Data.MySqlClient.MySqlException Error for no reason - c#

For the past month I've been getting data with a C# program in tandem with a company's API. Just yesterday all the sudden it would no longer work, even though I haven't changed the code at all. Here's the code:
public string GetMatchCode()
{
//this could be loaded from config file or other source
string connectString = "Server=123.123.1.23;Database=blah_users;Uid=blah_data;Pwd=blahblah;";
string sql = "SELECT MAX(match_id) FROM `data_blah`";
using (var connect = new MySqlConnection(connectString))
using (var command = new MySqlCommand(sql, connect))
{
connect.Open();
return command.ExecuteScalar().ToString();
}
}
And I get this error:
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Additional information: Access denied for user 'blah_data'#'cpe-86-80-21-54.san.res.rr.com' (using password: YES)
Any idea what could have happened and how to fix it? The only thing I think could've happened is that my support ticket dealing with node.js compatibility was executed wrong by support employees. Thanks!

Your db user's permission has failed. The user may have been removed; the permissions may have been modified. Contact the db owner.

So it looks like you are not authenticating: Either incorrect credentials or server needs a different method. Try disabling "sslmode" like below:
public string GetMatchCode()
{
//this could be loaded from config file or other source
string connectString = "Server=123.123.1.23;Database=blah_users;Uid=blah_data;Pwd=blahblah;sslmode=none;";
string sql = "SELECT MAX(match_id) FROM `data_blah`";
using (var connect = new MySqlConnection(connectString))
using (var command = new MySqlCommand(sql, connect))
{
connect.Open();
return command.ExecuteScalar().ToString();
}
}
That should do it

string sql = "SELECT MAX(match_id) FROM `data_blah`";
Isn't it supposed to be " ' " instead of " ` " surrounding "data_blah"?

Related

Usage of MySQL Parameter for creating new user

So I am using a MySQL Server version 8.0.16 and if I try to let dynamically create a new user, i do receive a Error message what says: >>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 '$password' at line 1<<.
What i can't understand, becouse if i replace the Parameters with the actual value and try it with the shell it works perfectly. I let my code connect as root so and checked if the connection is open what it is. So if I stepped into the code and checked if the parameters are correct everything looked fine. I also added >>'<< at the beginning and end of thext strings that should replace the parameters but it didn't changed the error or what happened.
public bool CreateNewUser(string name, string password, string host)
{
string query = "CREATE USER $name#$host IDENTIFIED BY $password;";
List<MySqlParameter> mies = new List<MySqlParameter>
{
new MySqlParameter("$name", name),
new MySqlParameter("$password", password),
new MySqlParameter("$host", host)
};
return InsertIntoQuery(query, mies);
}
//The InsertIntoQuery looks like this
private bool InsertIntoQuery(string sql, List<MySqlParameter> sqlParameters = null)
{
bool retBl = false;
try
{
using (var SqlConnection = new MySqlConnection(ConnectionStr))
{
SqlConnection.Open();
using (var cmd = new MySqlCommand(sql, SqlConnection))
{
if (sqlParameters != null)
foreach (var item in sqlParameters)
cmd.Parameters.AddWithValue(item.ParameterName, item.Value);
cmd.Prepare();
var retValNonQuery = cmd.ExecuteNonQuery();
retBl = (retValNonQuery > 0) ? true : false;
}
}
}
catch (Exception e)
{
MessageBox.Show("Error: " + e.Message);
}
return retBl;
}
I would expect it to create a new user but it doesn't.
No, for CREATE USER command I don't think you can pass command parameter likewise. Rather substitute the value as is like below using string interpolation syntax.
string query = $"CREATE USER '{name}#{host} IDENTIFIED BY {password}";
For an older C# version consider using string.Format()
string query = string.Format("CREATE USER '{0}'#'{1}' IDENTIFIED BY '{2}'",name,host,password);
Per OP's comment: You can't cause it's not a DML operation. If you are worried about SQL Injection probably cause input value is coming from user input then you will have sanitize it someway and moreover if you observe the input are quoted.
Again, I would suggest that this kind of admin operation should go in a DB bootstrap script and not in your application code.

Unable to query Oracle database via C# API

Good morning.
I am attempting to connect to an Oracle database I have set up. before I go into detail, here's the code:
//string was slightly altered.
string connectionString = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=name)));User Id = system; Password = mypass; ";
string toReturn = "D.BUG-";
using (OracleConnection oracleConnection = new OracleConnection(connectionString))
{
oracleConnection.Open();
using (OracleCommand oracleCommand = new OracleCommand())
{
oracleCommand.Connection = oracleConnection;
oracleCommand.CommandText = "SELECT lixo FROM lixeira WHERE lixo IS NOT NULL";
oracleCommand.CommandType = CommandType.Text;
using (OracleDataReader oracleDataReader = oracleCommand.ExecuteReader())
{
//This point IS reached!
while (oracleDataReader.Read())
//This point is never reached...
toReturn += oracleDataReader.GetString(0);
}
}
}
return toReturn;
Now, I know for a fact that connecting works, and I know for a fact that the table "lixeira" can be found; I have tested this by changing that name to another name, and getting the corresponding "i can't find that table" exception.
'ORA-00942: tabela ou visualização não existe'. (Table or View does not exist)
The issue is that this code is unable to read. The same query ran through SQL Developer works:
SQL Developer screenshot of the same query
So, I'm kinda at a loss as to why oracleDataReader.Read() just never works. Am I doing something wrong?
Make sure your user/password in the connection string is the correct one.
If a table doesn't exist but exists... it probably doesn't exist for your current user (= that user has not the necessary permissions)
Previous answer is correct, I am just adding another bit.
can you replace your query as following :
SELECT lixo FROM <table owner>.lixeira WHERE lixo IS NOT NULL
This will give more appropriate error of what you are missing.
Its probably a permission (grant select) issue.
Abhi

"The multi-part identifier could not be bound" sql, visual studio

I am just learning c# and sql server. This question has been asked a couple of times but the solutions posted don't seem to help me.
I have a table called "LoginInfo" that has a user's "email" and "pass".
In visual studio i have this method that checks a users login information
private boolean dbQueryLogin(string email, string password)
{
string com = "SELECT pass FROM LoginInfo WHERE email = XXXXX#yahoo.com";
SqlCommand command = new SqlCommand(com, conn);
SqlDataReader reader = command.ExecuteReader();
return reader.GetString(0).Equals(password);
}
This keeps on throwing the error "Additional information: The multi-part identifier "XXXX.edu" could not be bound."
The syntax looks right to me, is there anything i'm missing??
The clue is in the error message:
The multi-part identifier "XXXX.edu" could not be bound.
That strongly suggests that the problem isn't with identifying your table - it's with the bit that ends with "edu", which seems like to be an email address.
The immediate problem is that you've forgotten to quote a value. The deeper problem is that you should be using parameterized SQL anyway, to avoid SQL injection attacks, conversion problems and unreadable code. Given that the value you've given in the same code isn't the same as what's in the error message, I suspect you really have code like:
string sql = "SELECT pass FROM LoginInfo WHERE email = " + email;
Don't do that. Use parameterized SQL instead:
private boolean dbQueryLogin(string email, string password)
{
string sql = "SELECT pass FROM LoginInfo WHERE email = #email";
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand(sql))
{
command.Parameters.Add("#email", SqlDbType.NVarChar).Value = email;
using (var reader = command.ExecuteReader())
{
// FIXME: What do you want to do if
// there are no matches?
reader.Read();
return reader.GetString(0) == password;
}
}
}
}
This still isn't good code though:
Don't store plain-text passwords in a database
Handle the case where there are no results
Don't build your own authentication system at all; use an existing one written by people with more experience in securing data

MS Access OleDB object reference not set to an instance of an object

I have created a .Net 4.5 application that reads and writes to MS Access database. While running the application on my machine (which has MS office) everything is fine but when I run this on my server (which does not has MS Office but has ACE ) I get the object reference not set to an instance of an object.
This happens when I click the button. Following is the code
try
{
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
est_index = getTableIndex(conn,estimateTableIndex);
for (int i = 0; i < inputValues.Count; i++)
{
string FieldName = "";
string FieldValue = "";
if (inputValues[i] is System.Web.UI.WebControls.TextBox)
{
FieldName = inputValues[i].ClientID;
FieldValue = ((System.Web.UI.WebControls.TextBox)(inputValues[i])).Text;
}
else
{
FieldName = inputValues[i].ClientID;
FieldValue = ((System.Web.UI.WebControls.DropDownList)(inputValues[i])).SelectedValue;
}
//everything fine till here..then throws the error below
string my_querry = "INSERT INTO Estimate VALUES(#Est_id,#FieldName,#FieldValue)";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.Parameters.AddWithValue("#Est_id", est_index);
cmd.Parameters.AddWithValue("#FieldName", FieldName);
cmd.Parameters.AddWithValue("#FieldValue", FieldValue);
cmd.ExecuteNonQuery();
}
conn.Close();
}
catch (Exception e)
{
Console.Write(e.InnerException.Message);
}
Not sure why this is happening ?
EDIT: I created a virtual machine and downloaded the ACE and the same error occurred that clients face
EDIT 2: The connection string looks like "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\cohber.accdb"
I tried to debug and see where the code broke and it broke at cmd.ExecuteNonQuery();. The message at exception was operation must use an updateable query
Edit 3: the MS Access file is located in c driver. I gave all the users full permission but still get the error
You need to set read/ write permissions to the folder containing the access .mdb file

Additional information: Connection error: Trying to add unknown port '192.168.1.100'

static void Main(string[] args)
{
OleDbConnection conn = new OleDbConnection("Provider=SAOLEDB.10;LINKS=tcpip(IP=192.168.1.100,Port=2638);ENG=dental;Persist Security Info = True; User ID = dba; PWD = sql");
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT tran_num FROM transactions WHERE tran_date > '2015-10-01'", conn);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("{0}", reader.GetValue(0).ToString());
}
reader.Close();
conn.Close();
if (Debugger.IsAttached)
{
Console.ReadLine();
}
}
As the title suggests, I'm getting an error when attempting to connect to this server. The driver (Provider) works fine for a local database using the same server setup, trying to adjust the code to connect remotely to the same setup at a different location. This is an old SQL Anywhere 10 database and I've tried hard to find answers for this with no success so far.
Edit: I changed the string a little to reflect some suggestions, now just getting a new error: Additional information: Connection error: TCPIP requires a server name
Update: The syntax changes to LINKS seems to have progressed my attempts but now I'm having issues with the syntax it's looking for when searching for a server at that IP. Receiving an error: Additional information: Database server not found
This is the connection string in registry:
DBN=DENTSERV;DSN=DENTAL;UID=DBA;PWD=SQL
I've tried both ServerName= and ENG= using the DSN and DBN, also while having them in ' ' but still receiving that same error. Any thoughts?

Categories

Resources