Working with MySql database in C#/ Visual Studio - c#

Hello, I'm currently working on a project which contains a part in which you have to simply import data from database in different ways. My database is hosted on a local MySql server under localhost.
I want to know the most flexible and easy way to execute queries on my MySql database (of course in C# code). I've tried using string interpolation ($"" syntax) for modifying text of the query but I think it is not the best way to do this.
(its getting very complicated when you want to apply some more complex query)

cmd = new MySqlCommand("SELECT * FROM admin WHERE admin_username=#val1 AND admin_password=#val2", MySqlConn.conn);
cmd.Parameters.AddWithValue("#val1", "admin");
cmd.Parameters.AddWithValue("#val2", "pass");
cmd.Prepare();
MySqlDataReader res = cmd.ExecuteReader();

Related

Cannot find local database on WPF project in Visual Studio

I am trying to create a WPF application for a client and a SQL server is required. I am currently using Visual Studio to develop everything, but I have never used SQL servers outside of web application before. I add a new SQL database to my WPF project by adding a "Service-based Database", and everything works fine. Until I transfer the project over to a different computer where it crashes and gives me the error "System.Data.SqlClient.SqlException: Database not found". Is there something that I'm missing about setting up a database inside my VS project? Why does it only work on my development PC and not any other that I transfer it to?
The code that it crashes on:
string cn_string = Properties.Settings.Default.connection_String;
//Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\_data\db_local.mdf;Integrated Security=True
string cmdString = "SELECT * FROM tbl_Clients";
using (SqlConnection con = new SqlConnection(cn_string))
{
SqlCommand cmd = new SqlCommand(cmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("tbl_Clients");
sda.Fill(dt);
MyDataGrid.ItemsSource = dt.DefaultView;
}
Sorry for my easy questions, I am currently learning programming in high-school. Thanks for all your help.
Using a service-based database requires you to set up a SQL Server service on the machine where you intend to run the WPF client application.
If you want an embedded database that you can xcopy deploy with your application, you should take a look at SQLite. It is, unlike the service-based database that you create in Visual Studio, completely self-contained and doesn't require you to install any service.

Getting Transact SQL query result in C# Application

I'm trying to write a C# application that restores many databases from .bak files placed in a certain folder. To do so I need the databases logical name from the files.
So I want to execute the following query :
RESTORE FILELISTONLY FROM DISK = N'C:\Folder\File'
The problem is: I can't get the result of this to my application, when I execute it in SQL Server Management Studio, it shows the name I want.
I tried to use ExecuteReader function from SqlDataReader but it doesn't return any data.
Can someone help me figure out how to get the result of queries like restore database, backup database into a variable in a C# application ?
Thanks in advance
The command RESTORE FILELISTONLY does return a result set as per the documentation RESTORE Statement - FILELISTONLY. What I did find during testing my code, you need to make sure the user that is running the application has permissions to read the specified file and directory. Otherwise you will run into issues.
For a code example of this:
var command = #"RESTORE FILELISTONLY FROM DISK = N'F:\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\Scratch.bak'";
using (var sqlConnection = new SqlConnection("Server=localhost;Database=Scratch;Trusted_Connection=True;"))
using (var sqlCommand = new SqlCommand(command, sqlConnection))
{
sqlConnection.Open();
var sqlDataReader = sqlCommand.ExecuteReader();
while (sqlDataReader.Read())
{
Console.WriteLine($"Logical Name: {sqlDataReader["LogicalName"]}");
Console.WriteLine($"Physical Name: {sqlDataReader["PhysicalName"]}");
Console.WriteLine($"Type: {sqlDataReader["Type"]}");
}
}
You may also find that when trying to work SQL Server management, using the SqlConnection and SqlCommand objects may be more frustrating then they are worth. I strong recommend using the SQL Server Management Objects (SMO). This is actually what management studio uses when you are work with SQL Server. I have an example on GitHub if you are interested in it. Checkout GitHub: SMO Demo.

C# cannot insert data into SQL Server database

I'm recently new at C# and follow a tutorial on connection to the database, the connection for viewing or SELECT command was ok, I made some revision based on the threads of forums to make my code better, but when I was in INSERT for my SQL Server, I have some problems. I was able to insert the data but when I re-run the program the data that I just inserted earlier was not in the database.
Here is my code on insert
string commandText = "INSERT INTO loginInfo (name, pass, role) VALUES(#name, #pass, #role)";
using (connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#name", textBox1.Text);
command.Parameters.AddWithValue("#pass", textBox2.Text);
command.Parameters.AddWithValue("#role", textBox3.Text);
try
{
command.Connection.Open();
command.ExecuteNonQuery();
}
catch
{
}
finally
{
command.Connection.Close();
}
}
I'm trying to create a simple CRUD but not save the data... please help
If you're using the AttachDbFileName= clause in your connection string, you might have fallen victim to a well-known issue : you might just be looking at the wrong database (file) when checking your data.
When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the connection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The long-term viable solution in my opinion would be to:
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. YourDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=YourDatabase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.

Execute multistatement MySql through C#

I'm working with MySql database in C#.
I'm using MySql.Data.dll liibrary if that matters:
http://dev.mysql.com/downloads/connector/net/6.2.html
I wonder, may I execute several sql statements through single C# command
I tried something like:
string query = #"SELECT #id_article:= MAX(id_article) FROM articles WHERE name='abc';
INSERT INTO prices(id_article,price) VALUES (#id_article ,10);";
MySqlCommand cmd = new MySqlCommand(query, connMySQL);
cmd.ExecuteNonQuery();
I have more experience with Sql Server, something like this would work there.
Here I get syntax error. Still when I run these commands through SqlYog (a management software for MySql) they somehow worked.
Is it possible to execute such multicommand query in MySql and is it possible to do through .NET?
You use user variables in the query. So you must add parameter to connection string:
Allow User Variables=true
Multiple SQL statements are allowed by default ("AllowBatch" parameter).
More info at: MySQL Connector/Net Connection String Options Reference

Made this query in SQL Server Management Studio Express how to use it?

For my database I create a new query and wrote
select * from dbname
using SQL Server Management Studio Express 2005. Saved it by name SQLQuery1.sql on the desktop.
Now I would like to call this query from C# code when an ASP.NET button is clicked and display the results in a gridview.
How do I call the query? Can I tell Visual Studio 2008 to please execute the query stored in 'sqlquery1.sql' ?
Where do I store the results so that I can bind them the display controls like a gridview, or traverse the data?
This is a website in C#, ASP.NET, Visual Studio 2008, and database is on the same computer using SQL Server 2005 Express
You cannot just execute a SQL script you stored on your computer's desktop from an ASP.NET website.
You can either:
turn your query into a stored procedure in SQL Server, something like:
CREATE PROCEDURE dbo.proc_MyQuery
AS
SELECT (list of columns)
FROM dbo.MyTable
WHERE (condition)
When you do this, you can create a SqlCommand in your C# code and call that stored procedure and retrieve the results back.
or:
you can execute the query directly from your C# code by creating a SqlConnection and a SqlCommand object and running that SQL statement.
These are both absolutely basic ADO.NET features - you should find tons of learning resources online for this.
For instance:
ADO.NET 101 - Data Access with ADO.NET
ADO.NET 101: SQL Connection
ADO.NET 101: SqlCommand / Your guide to using this ADO.NET object to execute SQL Server commands
Using ADO.NET for beginners
ADO.NET for Beginners - Part 1
Which ever way you go, you basically need to have a SqlConnection to your database, and then a SqlCommand to execute the query. If you want to store the data so you can both bind it to a Gridview as well as navigate it in code, you probably want to store it in a DataTable. So your code would look something like this:
DataTable resultTable = new DataTable();
using(SqlConnection con = new SqlConnection("your connection string here"))
{
string sqlStmt = "SELECT (columns) FROM dbo.YourTable WHERE (condition)";
using(SqlCommand cmd = new SqlCommand(sqlStmt, con))
{
SqlDataAdapter dap = new SqlDataAdapter(cmd);
dap.Fill(resultTable);
}
}
and then to bind to the gridview, you'd use something like:
myGridView.DataSource = resultTable;
myGridView.DataBind();
and to navigate the DataTable, you can step through its .Rows() collection of data rows.
In your server side event handler you will need to open the file from the desktop, read in the SQL, and then use the SQL to databind the grid.
This would depend on the identity that the website code runs under having read access to the desktop. By default it won't so you would need to give that identity (NETWORK_SERVICE?) permission. This could open up horrible security holes.
You would be better off moving the SQL somewhere more accessible, like web.config, or a file in the website directory.

Categories

Resources