I have a bulk insert that works fine in SQL.
I can't figure out how to get the SQL code to work in C#.
CMD.CommandText = "???"
I've tried so many ideas and keep getting an error. The bulk insert is below:
Use Lab2
GO
BULK
INSERT [dbo].[tmpPerson]
FROM 'C:\Temp\Input2.txt'
WITH (
ROWTERMINATOR ='\n');
How about having a look at SqlBulkCopy Class
Lets you efficiently bulk load a SQL Server table with data from
another source.
Microsoft SQL Server includes a popular command-prompt utility named
bcp for moving data from one table to another, whether on a single
server or between servers. The SqlBulkCopy class lets you write
managed code solutions that provide similar functionality. There are
other ways to load data into a SQL Server table (INSERT statements,
for example), but SqlBulkCopy offers a significant performance
advantage over them.
I used the Server object in the Microsoft.SqlServer.management namespace to do this same kind of thing. It allows you to have the GO word in commands, where using the SqlCommand it expects that each instance of SqlCommand represents a single command.
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
Related
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
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.
I'm using Linq2Entity for most of my database operations. However for database creation, table creation and initial data insertion I use plain SQL files. Therefore I need both an SqlConnection and an EntityConnection. Unfortunately the Entity Framework starts complaining that the Sql Server is not listening on the other end of the pipe.
I'm not sure what the problem is here, it could be due to user instancing. Clearing the pool of the SqlConnection or disposing the connection instance does not help.
The connection string I'm using is the following:
"Data Source=.\SQLEXPRESS; Initial Catalog=dbname; Integrated Security=SSPI;"
update:
I have tried to use the EntityConnection for database maintenance purposes but I'm running into troubles. I can't use the EntityConnection to create databases and drop databases. The following syntax is unsupported for an EntityConnection but works fine for an SqlConnection to ms SQL express.
CREATE DATABASE silverfit ON ( NAME = silverfit, FILENAME = 'c:\silverfit\silverfit.mdf' );
Also for some reason the EntityConnection does not allow me to change databases which is necessary to drop a database. I'm afraid I still need the SqlConnection to create the database and tables..
Is there a way for SqlConnections and EntityConnections to coexist for local ms SQL express databases?
Thanks,
Wouter
Have you tried creating a SqlConnection which you then pass to the constructor for your EntityConnection? One of the overloads for EntityConnection takes a MetadataWorkspace and a DbConnection (from which SqlConnection derives.) The slight drawback of this is that you must create your MetadataWorkspace manually, which gathers up the .csdl, .ssdl, and .msl files that define your workspace. However, in the long run, you should be able to share a single connection for both executing DML queries, and using Entity Framework.
I don't agree that you need a plain SQL connection and Entity connection for this task, at least as you've described it. You can execute SQL using the Entity connection. Look at EntityConnection.CreateDbCommand. Naturally, there's a danger here that you are doing DB-server-specific things on a non-DB-server-specific instance like a EntityConnection. But it probably beats having a separate connection, in this case.
Did you try to use the EntityConnection.StoreConnection to retrieve the SqlConnection and execute commands with it ?
If you're trying attaching your database file to SQL Server Express at run time, which it seems as if you are, then only one connection can be open on it at once. This is a problem for other things, not just what you're trying to accomplish. Say, for instance, you connect to 'c:\silverfit\silverfit.mdf' through the server explorer in VS and try to open one of the tables in the db. After you open the table, try running your application. It will bomb.
However, if you open up SQL Management Studio Express (you can download it here), and then attach the database to the SQL Server, the problems you are experiencing should go away. At that point you should be able to open multiple connections to your database, via SQLConnection or EntityConnection.
Attaching your database at run time to the SQL Server express engine really only works well for demoing purposes, or proof of concepts.
Is ADO.NET holding a connection open to the database through connection pooling? Try adding Pooling=False to the connection string, as this may allow the database to be closed before you drop it.