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
Related
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();
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.
With SQL Server I run this query with no problem...
SELECT SUM(Esi) AS Dispo
FROM [mdb].[dbo].[Query1] AS A
INNER JOIN [mdb2].[dbo].[TieCol] as B ON A.Alias=B.IDAlias
WHERE Alias LIKE 'SETUP%'
I join two tables that reside in two different databases (mdb and mdb2).
But how can I do it in my .NET application?
When I need to use this statement
string cmdText = "SELECT SUM(Esi) AS Dispo
FROM [mdb].[dbo].[Query1] AS A
INNER JOIN [mdb2].[dbo].[TieCol] as B ON A.Alias=B.IDAlias
WHERE Alias LIKE 'SETUP%'";
this.OP = new SqlConnection(ConfigurationManager.ConnectionStrings["mdb2"].ConnectionString);
SqlCommand sqlCommand = new SqlCommand(cmdText, this.OP);
I can't execute it, since this.OP is the connection to mdb2... And for mdb?
How can I connect to both databases simultanously?
The SQL connection is to the server - the Initial catalog in a connection string behaves like use - it sets the default DB.
So your 3 part SQL query should work as is. So possibly
Make sure that the SQL login used by your app (or the account of your AppPool if using Web and Integrated Security) has the necessary access to both databases. (use RunAs on SQL Enterprise Manager as this account and try to run the query)
You might try escaping [Alias]
Also, if there is coupling between mdb1 and mdb2 (e.g. SPROCS in mdb1 use tables in mdb2 etc), for ease of maintenance, you might consider adding views in mdb1 for mdb2 objects. This allows for easy identification of cross-database dependencies. In this case, your query can use views which look like they are in the same database, although the underlying dependency on mdb2 is still there.
I'm not sure if there is a way to do this within the connection string. But you can probably do it using a four part reference to the table: [server].[database].[table].[column].
Your C# application only need to connect to one database server for this query.
Say your C# application connect to [mdb]. Database [mdb2] should b linked server in database [mdb].
Since you can run that query in sql server, so there must be one sql server connected to both databases. use that sql server in your C# connection string. That's it!
I'm writing an application that creates a SQL Server database for another program. For this I load a large SQL-script containing the CREATE DATABASE, CREATE TABLE and so on.
The first lines of the script is:
/*CREATE DATABASE*/
USE [master]
GO
CREATE DATABASE [MultiRisk5] COLLATE Latin1_General_CI_AS
GO
USE [MultiRisk5]
GO
And the C# code:
var sqlConn = new SqlConnection("myConnection");
var cmd = new SqlCommand("mySqlScript", sqlConn);
sqlConn.Open();
cmd.ExecuteNonQuery();
sqlConn.Close();
When I run the program I get an exception on the USE statement that tells me that the database MultiRisk5 doesn't exist.
How can this be, when I just created the database? The script runs fine when executed in SQL Server Management Studio.
You can't load a script in c# that has GO in it and run it.
GO is recognised the SQL Server client tools only, and as a batch separator. The database engine won't recognise it. See these questions for more on how to do this
Execute sql file on SQL Server using C#
Add column to table and then update it inside transaction
Also, does the SqlConnection try to connect to MultiRisk5? if so, this will error too before USE master is run
You may want to try executing your query in a try catch block to see what comes back. That would be a good first step into figuring out the issue.
Maybe your app does not have the appropriate rights to create the database ?
You should check whether the database creation succeeds before going on.
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.