I already have a MySQL db.
I would like to use WPF application in C#. I created the project and wrote the connection lines without errors.
How can I be sure that the connection goes okay? this code doens't returns errors but I would check the datas from the "query" cmd.
This is the connection code:
string connectionString = "SERVER=localhost;DATABASE=dbamne;UID=root;PASSWORD=pass;";
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand("SELECT * FROM table WHERE name = 'name';", connection);
connection.Open();
Basically you can check your connection using the method from example at MSDN:
// ...
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
}
But if you directly want execute your command you should use method ExecuteReader at command (or it async analog) like MSDN recomended:
// ...
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var command = new MySqlCommand("SELECT * FROM table WHERE name = 'name';", connection);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
/* This code shows just values from first column of your result table */
Console.WriteLine(reader[0]);
}
}
}
Related
How can I connect a SQL database in C#?
My code:
const string connectionString = "Data Source=127.0.0.1;User ID=root;Database=MyDatabase;Password=MyPassword";
var conn = new SqlConnection(connectionString);
conn.Open();
conn.Close();
I get: Error: 40 - could not open a connection to sql server. I tried also in Python and it worked well:
cnx = mysql.connector.connect(user='root', password='MyPassword', host='127.0.0.1', database='MyDatabase')
cursor = cnx.cursor()
What am I missing in C#?
Please use MySqlConnection for MySql DB.
const string connectionString = "Data Source=127.0.0.1;User ID=root;Database=MyDatabase;Password=MyPassword";
MySqlConnection conn = new MySqlConnection(connectionString );
conn.Open();
string sqlcommand = "SELECT Query";
MySqlCommand cmd = new MySqlCommand(sqlcommand , conn);
please follow this example
using MySql.Data.MySqlClient;
var connectionString = "server=serveradress;database=dbName;user id=sqluser;password=abc;";
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
using var command = new MySqlCommand("SELECT COUNT(*) FROM tableName ", connection);
var Count = command.ExecuteScalar();
Console.WriteLine($"There are {Count } movies");
}
server adress in general is 127.0.0.1 ,if you are working locally
here the source page :
example
and also consider reading this page here docs
The first SQL is executing but the second one doesn't seem to work.
When i change the query to the first one it works just fine but when I put it like that it doesn't seem to work for some reason.
I've just started learning MySQL i'm really struggling with this one and understanding the language.
//Classic One that checks if the hwid is there
public void checkHWID(string HWID)
{
string line;
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE HWID = #HWID", con))
{
cmd.Parameters.AddWithValue("#HWID", HWID);
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
line = reader[1].ToString();
Console.Write(line);
con.Close();
}
else
{
updateHWID(HWID);
}
}
}
}
}
//This one doesn't seem to update the hwid but when i change the query to the first one it works just fine
public void updateHWID(String HWID)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO USERS(hwid) VALUES(#HWID)", connection))
{
command.Parameters.AddWithValue("#HWID", HWID);
connection.Close();
}
}
}
Your SQL statement in the updateHWID function isn't working primarily because it is missing the code that executes the command you created.
connection.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO USERS(hwid) VALUES(#HWID)", connection))
{
command.Parameters.AddWithValue("#HWID", HWID);
command.ExecuteNonQuery(); // ADD THIS LINE
}
connection.Close();
Then assuming your table only requires the hwid and no other columns then this could work. If your table has other columns that don't allow nulls then you may get an error for the missing column values.
I'm playing around making a POC and I've created the following call.
public string DoStuff()
{
try
{
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
SqlConnection connection = new SqlConnection("Server...");
string command = "insert into Records values (...)";
adapter.InsertCommand = new SqlCommand(command, connection);
}
}
catch (Exception exception)
{
return exception.Message + " " + exception.InnerException;
}
return "WeeHee!";
}
The text I'm seeing returned is the happy one, so I conclude there's no exceptions. Hence, I conclude that the call to the DB is performed as supposed to. However, there's no new lines in the DB being created.
I'm using the same connection string as I have in my config file and the command in pasted in from SQL Manager, where it works.
So my suspicion was that although I create an insert command, I never actually execute it but according to MSDN that's how it's supposed to work.
What stupid thing do I miss here?
You are missing connection.Open(); and adapter.InsertCommand.ExecuteNonQuery();
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
SqlConnection connection = new SqlConnection("Server...");
connection.Open();
string command = "insert into Records values (...)";
adapter.InsertCommand = new SqlCommand(command, connection);
adapter.InsertCommand.ExecuteNonQuery();
}
You should use ExecuteNonQuery instead. Using an SqlDataAdapter for an INSERT query does not make sense.
Also you should Open your connection just before you execute it.
You can:
using(SqlConnection connection = new SqlConnection("Server..."))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = "insert into Records values (...)";
connection.Open();
int craeted = command.ExecuteNonQuery();
}
The example you linked to returned a SQLAdapter for later use.
You don't need one at all:
using (SqlConnection connection = new SqlConnection("Server..."))
{
string command = "insert into Records values (...)";
connection.Open();
var command = new SqlCommand(command, connection);
command.ExecuteNonQuery();
}
Note that there are other execution methods, depending on expected return values and whether you want asynchronous operation: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx
I have an ODBC connection to a database and I would like the user to be able to view data within any table. As this is an ASP.net application I cannot trust that the table name sent doesn't also contain nasties. I have tried using a parameterised query but I always get an error saying that I "Must declare the table variable" - this appears to be an issue because it is the table name
string sql = "SELECT TOP 10 * FROM ? ";
OdbcCommand command = new OdbcCommand(sql, dbConnection);
command.Parameters.Add(new OdbcParameter("#table", tableName));
OdbcDataAdapter adapter = new OdbcDataAdapter();
adapter.SelectCommand = command;
adapter.Fill(tableData);
What is the best method to achieve this in a secure way?
Use a stored procedure, it's the safest way.
Some hints:
You probably may also use the System.Data.SqlClient namespace objects
Enclose your connection, command and adapter objects initializations in using statements
Here's a simple example:
string sqlStoredProcedure = "SelectFromTable";
using (OdbcConnection dbConnection = new OdbcConnection(dbConnectionString))
{
dbConnection.Open();
using (OdbcCommand command = new OdbcCommand(sqlStoredProcedure, dbConnection))
{
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.Add(new OdbcParameter("#table", tableName));
using (OdbcDataAdapter adapter = new OdbcDataAdapter(command))
{
adapter.SelectCommand = command;
adapter.Fill(tableData);
}
}
}
Another way to go would be to retrieve all table names and validate the tableName string variable as an entry in the list, maybe using:
DataTable tables = dbConnection.GetSchema(OdbcMetaDataCollectionNames.Tables);
Here's a simple implementation based on your scenario:
string sql = "SELECT TOP 10 * FROM {0}";
using (OdbcConnection dbConnection = new OdbcConnection(dbConnectionString))
{
dbConnection.Open();
DataTable tables = dbConnection.GetSchema(OdbcMetaDataCollectionNames.Tables);
var matches = tables.Select(String.Format("TABLE_NAME = '{0}'", tableName));
//check if table exists
if (matches.Count() > 0)
{
using (OdbcCommand command = new OdbcCommand(String.Format(sql, tableName), dbConnection))
{
using (OdbcDataAdapter adapter = new OdbcDataAdapter(command))
{
adapter.SelectCommand = command;
adapter.Fill(tableData);
}
}
}
else
{
//handle invalid value
}
}
I have the following code behind a button in Visual Studio 2010
private void button1_Click(object sender, EventArgs e)
{
SqlCeConnection Con = new SqlCeConnection();
Con.ConnectionString = "Data Source = 'DB.sdf';" + "Password='my Password';";
SqlCeCommand Query = new SqlCeCommand("SELECT Password FROM Admin");
try
{
Con.Open();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
SqlCeDataReader Reader=Query.ExecuteReader();
MessageBox.Show(Reader["Password"].ToString());
}
It works fine execute and no exception in connection but when I press the button it raises an exception saying
Error: Execute Reader Connection Property Has Not Been Initialized
I'm not going to attempt to comment on database access code in a UI event handler, it will detract from the answer too much. All I will say is, try not to do it.
You haven't associated the connection with the command, either in the command constructor or the relevant Connection property.
I would re-write the entire method to the following to cut out the dangerous try-catch (catching everything, very bad practice) and to utilise the fact using statements also handle object disposal for you:
string password = null;
using (var conn = new SqlCeConnection("Data Source = 'AlviMBRental.sdf'; Password='my Password';"))
using (var comm = new SqlCeCommand("SELECT Password FROM Admin", conn))
{
conn.Open();
using (var reader = comm.ExecuteReader())
{
password = (string)reader["Password"];
} // Dispose reader
// Alternatively, if the resultset is single column and single row, you can do:
var passwordScalar = (string)comm.ExecuteScalar();
} // Dispose command, close / dispose connection.
MessageBox.Show(password ?? "No password found.");
You are not associating your command with your connection - try this:
SqlCeConnection Con = new SqlCeConnection("Data Source = 'AlviMBRental.sdf';Password='my Password';";
SqlCeCommand Query = new SqlCeCommand("SELECT Password FROM Admin", Con); // <== specify "Con" here!
Otherwise, your SqlCeCommand has no connection to work with....
Try like this:
private void button1_Click(object sender, EventArgs e)
{
var connectionString = "Data Source='AlviMBRental.sdf';Password='my Password';";
using (var con = new SqlCeConnection(connectionString))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "SELECT Password FROM Admin";
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
MessageBox.Show(reader["Password"].ToString())
}
}
}
}
Make sure you have associated the connection with the command object. Also make sure you have wrapped IDisposable objects in using statements as shown in my example.