How to avoid duplicated sql connection code - sql

So, I recently asked a question about a class called SQLHelper, that was designed to cut down duplicated code whenever you connect to a SQL server, create a stored procedure command, etc.
Essentially, from this:
string connectionString = (string)
ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand("INSERT_PERSON",connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#Name",SqlDbType.NVarChar,50));
command.Parameters["#Name"].Value = txtName.Text;
command.Parameters.Add(new SqlParameter("#Age",SqlDbType.NVarChar,10));
command.Parameters["#Age"].Value = txtAge.Text;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
...it would do this:
SqlHelper.ExecuteNonQuery(connection,"INSERT_PERSON",
new SqlParameter("#Name",txtName.Text), new SqlParameter("#Age",txtAge.Text));
Unfortunately the SQLHelper class vanished and is not available anymore in Enterprise library.
Would anybody know what could I use to avoid long code to set the connection up, create a store procedure, create parameters, set them, open the connection, execute the command and close the connection?
This would be required in each method that accesses that database and therefore is a considerable amount of duplicated code.
Is there way to avoid this?

Related

How to execute SQL query in ASP.NET MVC?

How to use this query in ASP.NET MVC to copy data from table and send it to another table?
INSERT INTO tblFee (AdmissionFee, Tuitionfee)
SELECT AdmissionFee, TuitionFee
FROM tblFee
Basically, you need a simple SqlConnection and SqlCommand to execute this query.
Done properly, it would look something like this:
string connectionString = "......"; // typically, you get this from a config file
string query = "INSERT INTO dbo.tblFee (AdmissionFee, Tuitionfee) SELECT AdmissionFee, TuitionFee FROM dbo.tblFee;";
// set up your connection and command, in "using" blocks
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmdInsert = new SqlCommand(conn, query))
{
// open connection, execute query, close connection
conn.Open();
// since you are doing an "INSERT" - use "ExecuteNonQuery"
// this returns only the number of rows inserted - no result set
int rowsInserted = cmdInsert.ExecuteNonQuery();
conn.Close();
}
But with this, you're really just duplicating every row that's already in dbo.tblFee and re-inserting them back into the same table .... is that really what you're looking for??

Execute stored procedure in EF Core 3.0 vs 2.2

I am trying to update my code to accommodate changes in EF Core 3.0, specifically the deprecation of ExecuteSqlCommand.
The following code was working in 2.2 but as stated, I need to get rid of ExecuteSqlCommand:
SqlParameter srcid = new SqlParameter("#srcCharacterId", participantApplication.CharacterId);
SqlParameter newid = new SqlParameter("#newCharacterId", newCharacterId);
SqlParameter pResult = new SqlParameter
{
ParameterName = "#pResult",
SqlDbType = System.Data.SqlDbType.Bit,
Direction = System.Data.ParameterDirection.Output
};
_db.Database.ExecuteSqlCommand("pCharacterCopy #srcCharacterId, #newCharacterId, #pResult OUTPUT", srcid, newid, pResult);
I've tried changing the call to ExecuteSqlRaw (leaving everything else identical) but that, although it compiles, throws the following exception at run time:
The SqlParameterCollection only accepts non-null SqlParameter type objects, not SqlParameter objects
I've checked with the debugger and none of the SqlParameter are null. I suspect my call to ExecuteSqlRaw is not formatted correctly but I cannot find any examples other than integrating calls into Linq queries which I don't need to do. I just want to fire off the call to the stored procedure and take a look at the output parameter when it is done.
This is most likely due to the switch to Microsoft.Data.SqlClient.
Remove the reference to the System.Data.SqlClient assembly and replace the namespaces.
using System.Data.SqlClient; => using Microsoft.Data.SqlClient;

Trouble establishing connection to Local SQL database

Simply trying to find out the correct syntax for my connection string. Before anyone asks, yes I did look at other SO answers, and no they did not work for me. Here a couple of attempts I made from looking at other SO questions like the one I am asking
Server=(local);Database=SalesOrdersExample;Integrated Security= true
Data Source=(local);Database=SalesOrdersExample;Integrated Security=SSPI
Server=.\\SQLEXPRESS;Database=SalesOrdersExampleDataSet;Integrated Security=true
None of them worked (I have a Console.WriteLine("test"); thrown in there and it works up until I try conn.Open() (opening the connection to database) so I'm assuming that it must be my connection string since nothing gets written after conn.Open())
Console.WriteLine("test"); // works
SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;Database=SalesOrdersExampleDataSet;Integrated Security=true");
Console.WriteLine("test"); // works
conn.Open();
Console.WriteLine("test"); // does not work
So some information about the database is that it's local under my 'Data Connections' in my Server Explorer. I also have the .xsd file in my project so I have linked the Data Set to the current project I am on. Here is a picture representation to confirm that I have both the Data Connection and the Data Set.
EDIT: SO does not allow me to post pictures until I have 10 rep so here is direct link to picture:
DB Screenshot
Any help is appreciated thank you.
Visual Studio comes with LocalDB database, which is not exactly SQL Server Express database.
Try something like this:
Server=(localdb)\v11.0;Integrated Security=true;
or
Data Source=(LocalDB)\v11.0; AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf; InitialCatalog=DatabaseName;Integrated Security=True;MultipleActiveResultSets=True
If using in c# code, you can use # to avoid problems with backslash characters:
SqlConnection conn =
new SqlConnection(#"Server=(localdb)\v11.0;Integrated Security=true;");

Import csv data from a secure url into a table

I have access to a system that if you enter in a url into a browser, it will automatically download a .csv file. The web address is formatted like below
https://secure.company.com/csv.cgi?user=username;password=password
What I would like to do is somehow get MS SQL Server 2012 to do all of the download and importing into a table automatically.
Is that even possible?
As a noob guess would it be done via a stored procedure?
If so how would one code such a thing?
How about using something like wget to download the file, then check out this blog post for how to import the CSV file into the database.
Even though there might be a way to send http request using SQL Server, using SQL queries, I’d strongly recommend you do this from C#. You can either develop a small application or use a CLR stored procedure for this.
Just update YourTable and download path and you should be fine.
protected const string FILE_NAME = #"C:\tablevalues.csv";
protected const string SQL_INSERT = "BULK INSERT YourTable FROM {0} WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')";
protected void DownloadFile()
{
WebClient webClient = new WebClient();
webClient.DownloadFile("https://secure.company.com/csv.cgi?user=username;password=password", FILE_NAME);
SqlConnection sqlConnection = new SqlConnection("connection string");
SqlCommand sqlCommand = new SqlCommand(string.Format(SQL_INSERT, FILE_NAME), sqlConnection);
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
sqlConnection.Dispose();
}

SQL Server 2008 Instance connection issue

My problem is the following:
I installes SQL Server 2008 R2 on my Windows Server 2008. I tried it by using default instance name (MSSQLSERVER) and named instance. The Installation was successful without an error. The problem is now:
When I try to connect to my SQL Server with the Management Studio it can't connect to this instance when I write "SERVER1\MSSQLSERVER" as serveraddress. When I write "SERVER1" only in the serveradress field it works.
Note: I always try to connect as SA. The password is right. Dont know if that matters...
But I have to be able to connect to "SERVER1\MSSQLSERVER" because I always get errors when I want to connect to a server without instance by C#.
Can someone tell me where I am mistaking?
EDIT:
The C# code looks like this:
sqlConnection = "data source=(local);persist security info=True;User ID=sa;Password=12345;initial catalog=BBKat"
SqlConnection sqlCon = new SqlConnection( sqlConnection );
SqlCommand sqlCmd = new SqlCommand( sqlCmdString, sqlCon );
I think you are not mistaken at all. You do not write the default instance name while connecting. You can create aliases though as mentioned above.
Try with a single (local) in the server name. and the same in C# web config connectionString as Data Source=(local);Initial Catalog=YOUR_DB;Integrated Security=True
EDIT
Change the connection string as:
data source=(local);Integrated Security=False;User ID=sa;Password=12345;initial catalog=BBKat