How to run sql script in c# - c#

I've searching for this and I thought I found the answer on here. this is the code I found to run a sql script through c#:
using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
namespace SeleniumTest2
{
class CreateSchema
{
public void Schema_Create()
{
string sqlConnectionString = "connection string here";
FileInfo file = new FileInfo(#"filepath to script.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
//DOESNTLIKE
server.ConnectionContext.ExecuteNonQuery(script);
file.OpenText().Close();
conn.Close();
}
}
}
But I keep getting the following error:
An unhandled exception of type 'Microsoft.SqlServer.Management.Common.ExecutionFailureException' occurred in Microsoft.SqlServer.ConnectionInfo.dll
Additional information: An exception occurred while executing a Transact-SQL statement or batch.
Can anyone tell me how to overcome this error?
THANKS!!

This happened to me a couple times. After debugging, there were some errors in my script file itself. The following worked for me:
Try running your script file directly using SQL Management Studio. This can pinpoint errors in your script itself.
Break down the SQL script into smaller files. For some reason this worked for me. Split the file into smaller scripts accordingly. For my particular database creation script, I separated it into a create tables script, a populate tables script, and an add primary and foreign keys script.
My code:
/// <summary>
/// Process SQL script with "GO" statements
/// </summary>
/// <param name="script"></param>
public static void ProcessSQLScriptFile(string script)
{
try
{
SqlConnection con = new SqlConnection(Properties.Settings.Default.SQLConDefault); // your connection string
con.Open();
Server server = new Server(new ServerConnection(con));
server.ConnectionContext.ExecuteNonQuery(script);
con.Close();
}
catch (SqlException e)
{
Console.WriteLine("SQL Exception: " + e.Message);
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
}
Hope this helps.

You may try this method to execute sql (from msdn):
private static void ExecuteCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
If you will get an error, check exception details, check if your connection string is valid.

I had this exact same issue. What fixed it for me was to find out the actual error:
public void Schema_Create()
{
string sqlConnectionString = "connection string here";
FileInfo file = new FileInfo(#"filepath to script.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
try
{
server.ConnectionContext.ExecuteNonQuery(script);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.InnerException.Message);
}
file.OpenText().Close();
conn.Close();
}
My issue presented itself in the ex.InnerException.Message, which in my case happened to be that my script was attempting to write a column that already existed on the table (column names must be unique for a given table).

Change the database path to another drive
Because in c drive or in windows drive you don't have permission to create data base
If change the path , your solution is work successful.

Related

CLR Stored Procedure Unable to connect with SqlConnection Regular Connection

I tried to create a CLR stored procedure in VS2017 but encountering error "NOT Connected." while executing that stored procedure.
I need to connect to other database server to grab some data. Therefore I cannot use context=true in SqlConnection.
Stored procedure will be created in serverA
This stored procedure will query data from serverB
Data will be stored back to serverA.
Is there anything I need to do in order to have regular connection in CLR stored procedure?
Please advise. Thanks!
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void udp_CLR_GetData()
{
string ConnStr = "server=MyServer; database=MyDB; user id=accabc; password=abc123";
string sql = " select top 1 ID from [dbo].Table1 ";
SqlDataReader dr = null;
DataTable dt = new DataTable();
try
{
using (SqlConnection fcon = new SqlConnection(ConnStr))
{
if (fcon.State == ConnectionState.Open)
{
SqlContext.Pipe.Send("Connected.");
using (SqlCommand fcmd = new SqlCommand(sql, fcon))
{
SqlContext.Pipe.Send("Before executing reader...");
dr = fcmd.ExecuteReader();
SqlContext.Pipe.Send("After executing reader...");
SqlContext.Pipe.Send("Before send...");
SqlContext.Pipe.Send(dr);
SqlContext.Pipe.Send("After send...");
}
}
else
{
SqlContext.Pipe.Send("NOT Connected.");
}
}
}
catch(Exception ex)
{
SqlContext.Pipe.Send("Exception error (udp_CLR_GetData): " + ex.Message);
}
finally
{
if(dr != null && !dr.IsClosed)
{
dr.Close();
}
}
}
}
Creating a new instance of a SqlConnection in:
using (SqlConnection fcon = new SqlConnection(ConnStr))
does not create it in an "open" state. You need to actually open it for it to be "open". So, I would remove the if (fcon.State == ConnectionState.Open) and the associated else part of it. I would also remove the SqlContext.Pipe.Send("Connected."); line.
Then, just before the dr = fcmd.ExecuteReader(); line, add a line for:
fcon.Open();
This way you open the connection and immediately execute the command. No need to open the connection only to do other work getting the command ready.
For more info on working with SQLCLR in general, please visit: SQLCLR Info
Try defining the data source in the connection string instead of server
string ConnStr = "DataSource=MyServer;Initial Catalog=MyDB;User Id=accabc;Password=abc123";
other than that, make sure clr is enabled on the server:
https://learn.microsoft.com/en-us/sql/relational-databases/clr-integration/clr-integration-enabling?view=sql-server-ver15

AdomdConnectionException was unhandled - The connection string is not valid

public static void connect()
{
try
{
string connectionStringStaging = #"Data Source=<server_name>;Catalog=<catalog_name>;User ID=<user_name>;Password=<my_password>";
string commandText = #"SELECT NON EMPTY { [Measures].[# Opptys moved to Committed] } ON COLUMNS FROM [Model]
CELL PROPERTIES VALUE, BACK_COLOR, FORE_COLOR, FORMATTED_VALUE, FORMAT_STRING, FONT_NAME, FONT_SIZE, FONT_FLAGS";
AdomdConnection connection = new AdomdConnection(connectionStringStaging);
connection.Open();
AdomdCommand cmd = new AdomdCommand(commandText);
cmd.Connection = connection;
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader[0]);
}
}
}
catch (AdomdConnectionException ex)
{
Console.WriteLine("Error : " + ex.ToString());
}
}
I am using the above code to connect to server and then I am further running MDX queries using this.The problem is the error I am getting - "The connection string is not valid" at line
connection.open();
Are the settings name incorrect which I am using in my connection string?Can someone help me figure out what is wrong in my connection string ?
The stack trace is as follows:
Please consult the following documentation from Microsoft: https://msdn.microsoft.com/en-us/library/microsoft.analysisservices.adomdclient.adomdconnection.connectionstring.aspx
You can also find some examples of connection strings here: https://www.connectionstrings.com/adomd-net/
Hope this will help you sort the problem.
I found my answer here. The unofficial package worked just fine . So I installed the reference Unofficial.Microsoft.AnalysisServices.AdomdClient and so the problem was not in the connection string but in the package.

Restore MSSQL database on remote machine from backup file via C# code

I have a mssql database on remote machine and backup file for this database. I want to create a method (c#) for restoring of database from backup. I will execute my method on my local machine. Can somebody help me to create such method for restoring remote database?
Try the this:
public void RestoreDatabase(string fileName)
{
try
{
using (SqlConnection conn = new SqlConnection("connectionString"))
{
string sql = "RESTORE DATABASE YourDatabase FROM DISK = N''" + fileName;
conn.Open();
SqlCommand _command = new SqlCommand(sql, conn);
_command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
throw;
}
}
You call it this way :
RestoreDatabase(#"\\remotemachine\...\YourFile.bak");
NB: Put an actual path for where the file is located

SQL connection string in web service c#

Hi I'm having a problem finding the correct connection statement for my web-service to an sql-server database. I'm trying to retrieve data from my database to check a users login details.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace BTC_Service
{
public class UseDatabase
{
SqlConnection sqlConn;
internal Boolean Connect()
{
try
{
sqlConn = new SqlConnection(#"Integrated Security=true; Initial Catalog=BTCFS_DataBase; Data Source=.\SQLEXPRESS;");
sqlConn.Open();
return true;
}
catch (SqlException ex)
{
return false;
}
}
internal void DisconnectDatabase()
{
sqlConn.Close();
}
internal Boolean ExecuteCommand(String query)
{
try
{
SqlCommand cmd = sqlConn.CreateCommand();
cmd.CommandText = query;
cmd.ExecuteNonQuery();
return true;
}
catch (SqlException ex)
{
return false;
}
}
internal SqlDataReader ExecuteQuery(String query)
{
try
{
SqlCommand cmd = sqlConn.CreateCommand();
cmd.CommandText = query;
return cmd.ExecuteReader();
}
catch (SqlException ex)
{
return null;
}
}
}
}
The database is created with sql-server 2008 and the path for it is:
C:\BTCFS_DataBase\db_BTDC_data.mdf
and the log file
C:\BTCFS_DataBase\db_BTDC_log.ldf
There is no password for the database and the code is as follows:
USE master
GO
create database db_BTCFC
ON PRIMARY
(
NAME = 'db_BTCFC_Data',
FILENAME = 'c:\BTCFS_DataBase\db_BTDC_data.mdf',
SIZE = 5MB,
FILEGROWTH = 10%
)
LOG ON
(
NAME = 'db_BTFC_log',
FILENAME = 'c:\BTCFS_DataBase\db_BTDC_log.ldf',
SIZE = 5MB,
FILEGROWTH = 10%
)
GO
Is there any suggestion to what I am doing wrong?
Should I add the database to visual studio in a specific way?
Or am i creating my database in the wrong way?
Thank you in advance.
The fact that you are connected using Integrated Security, means that your local user account on Windows should be authenticated on the SQL server instance which is hosted locally on your machine (evident by the "." in the Data Source, which refers to your local machine). It might be that the setup of your SQL server instance doesn't accommodate windows authentication. Check that your configuration allows for "mixed mode" authentication, i.e. either Windows authentication or username/password authentication...
I found this statement to be more effective than the previous one:
sqlConn = new SqlConnection(#"Integrated Security=SSPI; Initial Catalog=BTCFS_DataBase; Data Source=localhost");
Thanks #Wolfish for the link.

Is it possible to output the results of an sql command to a text file, when sent via SMO in C#?

I am using SMO in C# to run an SQL script. I need to output the results of the file into a text file.
When using a command line to run the query I can get the desired result using the "-o [output file]" argument. Is there a way to carry out the same operation using an SMO object?
At the moment my code simply sends an sql script to a server:
// Read the sql file
string script = sqlFile.OpenText().ReadToEnd();
// Create a new sql connection, and parse this into a server connection.
SqlConnection sqlConnection = new SqlConnection(connectionString);
Server server = new Server(new ServerConnection(sqlConnection));
// Run the sql command.
server.ConnectionContext.ExecuteNonQuery(script);
Any help would be much appreciated!
I don't know if you can do the exact same thing, but assuming that the script returns some data you could just execute the script, read the returned data and store it to a file, for example:
using (StreamWriter sw = new StreamWriter("output.txt"))
{
using(SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using(SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = script;
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
sw.WriteLine(rdr.Item("colName").ToString();
}
}
}
}
}
Discovered that the SQL script that I needed to execute basically only outputted errors it encountered into the output file. I was able to catch this using:
catch (Exception ex)
{
executedSuccessfully = false;
SqlException sqlex = ex.InnerException as SqlException;
if (sqlex != null)
{
exceptionText = sqlex.Message;
}
}
Thanks for your help though Ho! I may need this in the future...

Categories