Can't make SQL Server connection C# - c#

I'm trying to connect to a SQL Server on a local machine, run a SQL command against it and log the results. The code keeps failing at making the connection to the server.
I can't quite see what I'm doing wrong. Everything I've searched for either doesn't apply to this method or seems to match what I'm doing. I think I have other problems in the code as well, but I can't even get past the SQL connection to test the rest. Here is my code:
string svrConnection = "Server=.\\sqlexpress;Database="+db+";User ID=user;Password=password;";
SqlConnection con;
SqlCommand cmd;
Directory.CreateDirectory("C:\\"db"\\");
FileInfo file = new FileInfo("C:\\script.sql");
string PCS = file.OpenText().ReadToEnd();
con = new SqlConnection(svrConnection);
StreamWriter PCSLog = new StreamWriter(#"C:\\" + db + "\\Log" + db + ".txt");
try
{
con.Open();
cmd = new SqlCommand(PCS, con);
cmd.ExecuteNonQuery();
using (SqlDataReader pcsrdr = cmd.ExecuteReader())
using (PCSLog)
{
while (pcsrdr.Read())
PCSLog.WriteLine(pcsrdr[0].ToString() + pcsrdr[1].ToString() + ",");
}
PCSLog.Close();
cmd.Dispose();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection !", ex.Message);
}

There are additional problems with your code:
The Lines
cmd.Dispose();
con.Close();
are not guaranteed to execute if an exception occurs.
You call PCSLog.Close AFTER after you have disposed of it
I would suggest this as a better alternative (irrespective of the other comments made here).
string svrConnection = "Server=.\\sqlexpress;Database="+db+";User ID=user;Password=password;";
Directory.CreateDirectory("C:\\" + db + "\\");
FileInfo file = new FileInfo("C:\\script.sql");
string PCS = file.OpenText().ReadToEnd();
try
{
using (SqlConnection con = new SqlConnection(svrConnection))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(PCS, con))
{
cmd.ExecuteNonQuery();
using (SqlDataReader pcsrdr = cmd.ExecuteReader())
using (StreamWriter PCSLog = new StreamWriter("C:\\" + db + "\\Log" + db + ".txt"))
{
while (pcsrdr.Read())
PCSLog.WriteLine(pcsrdr[0].ToString() + pcsrdr[1].ToString() + ",");
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection !", ex.Message);
}

I think the issue is your connection string. Try this:
string svrConnection = "Data Source=.\\SQLEXPRESS;Initial Catalog=" + db + ";User Id=user;Password=password;"
Or to get a connection using your windows credentials:
string svrConnection = "Data Source=.\\SQLEXPRESS;Initial Catalog=" + db + ";Trusted_Connection=True;"
Also, ExecuteNonQuery does not run each command separated by GO. You will need to split your query into sections and run each individually.

Related

SqlConnection in VS2015 C#

I am extremely new to C# web development (or any development for that matter) but I am trying to figure out how to save the results from a SQL query to a variable. I think I understand the process, but many of the examples I am finding on the Web use a SqlConnection statement. My copy of Visual Studio does not seem to have that command (pretty sure I am using the wrong word here). What am I missing either softwarewise or knowledgewise accomplish my task?
Thank you in advance for your help.
Dep
It depends on what you want to do: insert, update, get data. It also depends if you want to use an ORM library or not. I all depends. The code that I copy below is an example of how to retrieve a DataTable using Ado.Net (as you mentioned SqlConnection):
You have to use:
using System.Data;
using System.Data.SqlClient;
This is the code for retrieving a DataTable
private DataSet ExecuteDataset(string query)
{
var conn = new SqlConnection("Data Source=" + Server + ";Initial Catalog=" + Database + ";User Id=" + Username + ";Password=" + Password + ";");
DataSet ds;
try
{
conn.Open();
ds = new DataSet();
var da = new SqlDataAdapter(query, conn);
da.Fill(ds);
}
catch (Exception)
{
throw;
}
finally
{
conn.Dispose();
conn.Close();
}
return ds;
}
private DataSet ExecuteDataset(string query, SqlParameter[] parametros)
{
var conn = new SqlConnection("Data Source=" + Server + ";Initial Catalog=" + Database + ";User Id=" + Username + ";Password=" + Password + ";");
DataSet ds;
try
{
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = query;
foreach (SqlParameter p in parametros)
{
command.Parameters.Add(p);
}
ds = new DataSet();
var da = new SqlDataAdapter(command);
da.Fill(ds);
}
catch (Exception)
{
throw;
}
finally
{
conn.Dispose();
conn.Close();
}
return ds;
}
This is the code for running a query that does not expect result with and without parameters:
private void ExecuteNonQuery(string query)
{
var conn = new SqlConnection("Data Source=" + Server + ";Initial Catalog=" + Database + ";User Id=" + Username + ";Password=" + Password + ";");
try
{
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = query;
command.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
conn.Dispose();
conn.Close();
}
}
private void ExecuteNonQuery(string query, SqlParameter[] parametros)
{
var conn = new SqlConnection("Data Source=" + Server + ";Initial Catalog=" + Database + ";User Id=" + Username + ";Password=" + Password + ";");
try
{
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = query;
foreach (SqlParameter p in parametros)
{
command.Parameters.Add(p);
}
command.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
conn.Dispose();
conn.Close();
}
}
Here is the simplest example I can think of, take note of the using statements and comments
using System;
using System.Data;
using System.Data.SqlClient;
namespace DataAccess
{
class Program
{
static void Main(string[] args)
{
//Use your database details here.
var connString = #"Server=localhost\SQL2014;Database=AdventureWorks2012;Trusted_Connection=True;";
//Enter query here, ExecuteScalar returns first column first row only
//If you need to return more records use ExecuteReader/ExecuteNonQuery instead
var query = #"SELECT [AccountNumber]
FROM [Purchasing].[Vendor]
where Name = #Name";
string accountNumber = string.Empty;
//Using statement automatically closes the connection so you don't need to call conn.Close()
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(query, conn);
//Replace #Name as parameter to avoid dependency injection
cmd.Parameters.Add("#Name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = "Michael";
try
{
conn.Open();
//Cast the return value to the string, if it's an integer then use (int)
accountNumber = (string)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Console.WriteLine(accountNumber);
//ReadKey just to keep the console from closing
Console.ReadKey();
}
}
}
If you are really new to C# with SQL Server, I would recommend to start from scratch using one of the tutorials shown here. It provides a lot of information in a step-by-step manner:
The basics
Clearly definition of the core ceoncepts
How to setup dependencies to get started
How to choose between development models (code, model vs. database first)
How to write queries
and much more.
Using SqlConnection is a valid choice, but requires more effort in writing the queries for doing basic stuff like selecting, updating, deleting or inserting data. You actually have to construct the queries and take care to build and dispose the commands.
On a related note:
The new way of doing all database-related activities in C# or .NET would be to harness Entity Framework (EF), and try to move away from any ADO.NET-based code. The latter still exists and hasn't been marked as obsolete, though. You may want to use ADO.NET for small apps or for any PoC tasks. But, otherwise, EF is the way to go.
EF is an ORM, and is indeed built as a repository pattern and generates a conceptual layer for us to work with. All of the nuances of the connection and command are completely encapsulated from us. This way, we don't have to meddle with these bare-bones.
If you want to do it well, you have to edit a file named Web.config in your project and put something like this inside (with your own DB data):
<connectionStrings >
<add
name="myConnectionString"
connectionString="Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
Then, in the code, you can use it with:
SqlConnection con = new SqlConnection(
WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
Finally you can do that you want with "con", for example:
string queryString = "SELECT name, surname FROM employees";
SqlCommand command = new SqlCommand(queryString, con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader["name"], reader["surname"]));
}
}
finally
{
reader.Close();
}
i use this nuget library.
https://www.nuget.org/packages/SqlServerDB_dotNET/
using SqlServerDB;
string server = #"INSTANCE\SQLEXPRESS";
string database = "DEMODB";
string username = "sa";
string password = "";
string connectionString = #"Data Source="+ server + ";Initial Catalog="+ database + "; Trusted_Connection=True;User ID="+ username + ";Password="+ password + "";
DBConnection db_conn = new DBConnection(connectionString);
Console.WriteLine("IsConnected: " + db_conn.IsConnected());
if (db_conn == null || !db_conn.IsConnected())
{
Console.WriteLine("Connessione non valida.");
return;
}
string sql = "SELECT ID, Message FROM Logs ORDER BY IDLic;";
DataTable dtLogs = db_conn.SelectTable(sql);
if (dtLogs == null || dtLogs.Rows.Count == 0)
return;
// Loop with the foreach keyword.
foreach (DataRow dr in dtLogs.Rows)
{
Console.WriteLine("Message: " + dr["Message"].ToString().Trim());
}

Retrieve data from database using C#

I'm trying to retrieve data from database in Microsoft visual studio 2013 . I am totally lost whether I am already able to connect to the database or not and I am not sure how to retrieve data using c# as I am totally new to c#.
I am also not sure where I should put the static void main method statement before or after connectDB() method.
private void connectDB()
{
// server = "172.20.129.159";
database = "eyetracker";
server = "localhost";
// uid = "ogamaaccess";
// password = "ogama";
uid = "root";
password = "root";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
c = new MySqlConnection(connectionString);
Console.WriteLine("Connected to database");
}
private bool OpenConnection()
{
try
{
c.Open();
Console.WriteLine("Connection Opened.");
return true;
}
catch (MySqlException)
{
return false;
}
You need to install the MySql NET Connector that provides the appropriate bits to connect to MySQL database.
After installing the provider you need to add a reference to MySql.Data.Dll and add the appropriate using statement to your code
using MySql.Data.MySqlClient;
You also need to change your connection string which could be found in here.
Connection code should look something close to this:
private void Login() // login method
{
string connectString = #"uid=<UserID>;password=<Password>;
server=<IPorDomainNameOfDatabase>;
database=<DatabaseNameOnServer>;";;
using(MySqlConnection cnn = new MySqlConnection(connectString))
{
try
{
cnn.Open();
}
catch (Exception e)
{
.....
}
}
}
Full code could look something like this (command should be edited according to data you want to retrieve):
MySqlConnection connect = new MySqlConnection(connectString);
MySqlCommand command = connect.CreateCommand();
command.CommandText = "Select <VALUE> from <TABLE> order by <ID> desc limit <0,1>;";
//Command to get query needed value from DataBase
connect.Open();
MySqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
var result = reader.GetString(0);
}
Note: I strongly suggest you to put connect.Open(); into TryCatch statment, since there are many things that can do wrong and your program will crash.

format of the initialization string does not conform to specification at index 33

I have a simple query to update the users information however i get the error stating 'format of the initialization string does not conform to specification at index 33' and it seems to highlight this specific code Connection.Close(); however im not sure why, here is the complete code:
public void AddNewUser()
{
string filePath;
try
{
filePath = (Application.StartupPath + ("\\" + DBFile));
connection = new System.Data.OleDb.OleDbConnection((ConnectionString + filePath));
connection.Open();
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
// ---set the user's particulars in the table---
string sql = ("UPDATE enroll SET SSN=\'"
+ (txtSSN.Text + ("\', " + ("FirstName=\'"
+ (txtFirstName.Text + ("\', " + ("LastName=\'"
+ (txtLastName.Text + ("\' "
+ (" WHERE ID=" + _UserID))))))))));
command.CommandText = sql;
command.ExecuteNonQuery();
MessageBox.Show("Student added successfully!", "Registered");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error");
}
finally
{
connection.Close();
}
}
EDIT:
Here are the file paths:
const string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"C:\\Users\\Zack\\My Documents\\Test\\Database.mdb";
const string DBFile = "C:\\Users\\Zack\\My Documents\\Test\\Database.mdb";
Your command text is wrong and you should use parametirized queries, here is correct version:
command.CommandText = "UPDATE enroll SET SSN= #ssn, FirstName = #fname, LastName = #lastName WHERE ID = #id";
command.Parameters.AddWithValue("#ssn", txtSSN.Text);
command.Parameters.AddWithValue("#fname", txtFirstName.Text);
command.Parameters.AddWithValue("#lastName", txtLastName.Text);
command.Parameters.AddWithValue("#id", _UserID);
And connection string:
string conString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='C:\Users\Zack\My Documents\Test\Database.mdb'";
Zack,
There are quite a number of issues with this code. Primarly if you were to run this (as SLacks states) you are open to sql injection attacks. (Read up on it).
First off.. Your connection string (based on your code) when run will be.
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"C:\\Users\\Zack\\My Documents\\Test\\Database.mdb\\C:\\Users\\Zack\\My Documents\\Test\\bin\Debug\\C:\\Users\\Zack\\My Documents\\Test\\Database.mdb
Well that is a guess. You should be using the following (note your path is hard coded).
const string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"{0}\"";
const string DBFile = "Database.mdb";
//...
var connection = new System.Data.OleDb.OleDbConnection(ConnectionString)
If you wanted to make your connection string dynamic to the path try this.
string conString = string.Format(ConnectionString, Path.Combine(Application.StartupPath, DBFile));
var connection = new System.Data.OleDb.OleDbConnection(conString);
This should set your connection string properly to you application startup. Now you may find it more useful to work of the executing assembly path as opposed to the application startup (your call).
Next your queries are a mess. I have cleaned it up to use parameterized queries instead with the resulting code somthing like. (note this has not been tested).
const string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"{0}\"";
const string DBFile = "Database.mdb";
public void AddNewUser()
{
string conString = string.Format(ConnectionString, Path.Combine(Application.StartupPath, DBFile));
using (var connection = new System.Data.OleDb.OleDbConnection(conString))
{
try
{
string sql = "UPDATE enroll SET SSN=#ssn, FirstName=#firstName, LastName=#lastName WHERE ID=#userID";
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand(sql, connection);
command.Parameters.AddWithValue("#ssn", txtSSN.Text);
command.Parameters.AddWithValue("#firstName", txtFirstName.Text);
command.Parameters.AddWithValue("#lastName", txtLastName.Text);
command.Parameters.AddWithValue("#userID", _UserID);
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("Student added successfully!", "Registered");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error");
}
finally
{
connection.Close();
}
}
}
EDIT:
I created a test lab for the code above and all ran correctly. Let me know if you have any questions.
Cheers.

C# access database error

This code when used in MS-Access is running and updating in property, but when using through database it's giving syntax error
string item = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
string h="update Follow_Date set Current_Date='" + dateTimePicker1.Value.ToLongDateString() + "', Current_Time='" + dateTimePicker3.Value.ToLongTimeString() + "', Type='" +
comboBox1.SelectedItem.ToString() + "', Remarks='" +
textBox1.Text + "', Next_Follow_Date='" + dateTimePicker2.Value.ToLongDateString()+ "' where Follow_Id='" +
item.ToString() +"'";
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\lernovo\Documents\JDB.mdb");
con.Open();
OleDbCommand cmd = new OleDbCommand(h, con);
cmd.ExecuteNonQuery();
Error is syntax error.
string item = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
string h="update Follow_Date set #Current_Date, #Current_Time, #Type, #Remarks, #Next_Follow_Date where #Follow_Id";
try
{
Using (OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\lernovo\Documents\JDB.mdb"))
{
con.Open();
Using (OleDbCommand cmd = new OleDbCommand(h, con))
{
cmd.Parameters.Add("Current_Date", dateTimePicker1.Value.ToLongDateString());
cmd.Parameters.Add("Current_Time", dateTimePicker3.Value.ToLongTimeString());
cmd.Parameters.Add("Remarks", textBox1.Text);
cmd.Parameters.Add("Type", comboBox1.SelectedItem.ToString());
cmd.Parameters.Add("Next_Follow_Date", dateTimePicker2.Value.ToLongDateString());
cmd.Parameters.Add("Follow_Id", item.ToString());
cmd.ExecuteNonQuery();
}
}
}
catch(SQLException ex)
{
System.Console.WriteLine(ex.Message, ex.StackaTrace)
}
You're not closing your Database connection and try to use Parameter instead of concatenation(Probe to SQL Injection).
Catch your error message and it trace it using StackTrace. Try to use Using statement to dispose object properly.
Looks like a trivial mistake...
You must have to open the db connection before executing queries on it..
conn=new conn(db param);
try
{
conn.open()
}
catch(Exception e)
{
e.getMessage();
}

How to backup database (SQL Server 2008) in C# without using SMO?

I have this code and it is not working but I don't why?
try
{
saveFileDialog1.Filter = "SQL Server database backup files|*.bak";
saveFileDialog1.Title = "Database Backup";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
SqlCommand bu2 = new SqlCommand();
SqlConnection s = new SqlConnection("Data Source=M1-PC;Initial Catalog=master;Integrated Security=True;Pooling=False");
bu2.CommandText = String.Format("BACKUP DATABASE LA TO DISK='{0}'", saveFileDialog1.FileName);
s.Open();
bu2.ExecuteNonQuery();
s.Close();
MessageBox.Show("ok");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
and I get this error :
What is the problem?
You need to assign that SqlConnection object to the SqlCommand - try this code:
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string connStr = "Data Source=M1-PC;Initial Catalog=master;Integrated Security=True;Pooling=False";
using(SqlConnection conn = new SqlConnection(connStr))
{
string sqlStmt = String.Format("BACKUP DATABASE LA TO DISK='{0}'", saveFileDialog1.FileName);
using(SqlCommand bu2 = new SqlCommand(sqlStmt, conn))
{
conn.Open();
bu2.ExecuteNonQuery();
conn.Close();
MessageBox.Show("ok");
}
}
}
You never tell your SqlCommand which connection to use (this is what the error message says by the way, did you read it?). Either set the Connection property or use SqlConnection.CreateCommand to create the command in the first place.
Backup Sql Server 2008 database in C#(100% correct)
using System.Data.SqlClient;
try{
SqlConnection con = new SqlConnection(cs.conn());
string database = con.Database.ToString();
string datasource = con.DataSource.ToString();
string connection = con.ConnectionString.ToString();
string file_name =data_loaction+database_name;
--- "D:\\Hotel BackUp\\" + database + day + month + year + hour + minute + second + ms + ".bak";
con.Close();
con.Open();
string str = "Backup Database [" + database + "] To Disk =N'" + file_name + "'";// With Format;' + char(13),'') From Master..Sysdatabases Where [Name] Not In ('tempdb','master','model','msdb') and databasepropertyex ([Name],'Status') = 'online'";
SqlCommand cmd1 = new SqlCommand(str, con);
int s1 = cmd1.ExecuteNonQuery();
con.Close();
if (s1 >= -1)
MessageBox.Show("Database Backup Sucessfull.", "Hotel Management", MessageBoxButtons.OK, MessageBoxIcon.Information);
else{
MessageBox.Show("Database Backup Not Sucessfull.", "Hotel Management", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}

Categories