Connecting to sql server 2008 database using C# - c#

I tried connecting using a connection string and get this error:
"Format of the initialization string does not conform to specification starting at index 0."
here is my code :
SqlConnection Con = new SqlConnection(#"C:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL10.SQLEXPRESS\MSSQL\DATA\TARGIL3.MDF");
SqlDataAdapter adapt = new SqlDataAdapter();
adapt.InsertCommand = new SqlCommand(" INSERT INTO tblEmployee VALUES (#employeeNumber, #employeePrivateName, #employeeFamilyName ,#city, #street, #houseNo, #phoneNumber, #birthDate, #startWorkingDate)", Con);
adapt.InsertCommand.Parameters.Add("#employeeNumber", SqlDbType.Char).Value = textBox1.Text;
adapt.InsertCommand.Parameters.Add("#employeePrivateName", SqlDbType.VarChar).Value = textBox2.Text;
adapt.InsertCommand.Parameters.Add("#employeeFamilyName", SqlDbType.VarChar).Value = textBox3.Text;
adapt.InsertCommand.Parameters.Add("#city", SqlDbType.VarChar).Value = textBox4.Text;
adapt.InsertCommand.Parameters.Add("#street", SqlDbType.VarChar).Value = textBox5.Text;
adapt.InsertCommand.Parameters.Add("#houseNo", SqlDbType.Int).Value = textBox6.Text;
adapt.InsertCommand.Parameters.Add("#phoneNumber", SqlDbType.Char).Value = textBox7.Text;
adapt.InsertCommand.Parameters.Add("#birthDate", SqlDbType.DateTime).Value = Convert.ToDateTime(textBox8.Text);
adapt.InsertCommand.Parameters.Add("#startWorkingDate", SqlDbType.DateTime).Value = Convert.ToDateTime(textBox8.Text);
Con.Open();
adapt.InsertCommand.ExecuteNonQuery();
Con.Close();

use this:
string connString = "Data Source=SERVERNAME;Initial Catalog=DATABASENAME; User ID = USERNAME; Password=PASSWORD;Integrated Security=false";
SqlConnection Con = new SqlConnection(connString);

You connection string is wrong. It should be of this form if you use SQL Server Authentication:
Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;
Where myServerAddress is the IP or host name of the computer running SQL Server. If it's your PC, localhost will probably work.
myUsername and myPassword are the credentials of the user connecting to the server.
If you use Trusted Connection,you connection string should be of this form:
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
You can check more examples here: http://www.connectionstrings.com/sql-server/

You cannot just put a file name in the connection string
C:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL10.SQLEXPRESS\MSSQL\DATA\TARGIL3.MDF
Sql Server is a usually a "service", and you talk to the service..........
Now. If you are using "Express" version......then you may have to include the AttachDbFilename parameter.
http://www.connectionstrings.com/sqlconnection/attach-a-database-file-on-connect-to-a-local-sql-server-express-instance-1/
Server=.\SQLExpress;AttachDbFilename=C:\MyFolder\MyDataFile.mdf;Database=dbname;
Trusted_Connection=Yes;
But if you are NOT using "Express", then you should only put info about the Sql Server SERVICE (machine\instancename, etc, etc), and not care about the physical path of the .MDF.
Sql Server is not JET (Access). With JET, you would only specify the filename.
If you're still having issues, you should post which version of sql server you are using.....do a "select ##version" and report that.

Related

MS SQL ODBC Connection with NO Windows Authentication

I'm trying to connect to MS SQL using ODBC but keep getting the
"Login failed for user 'User-PC\User'" error.
web.config
<add name="SQLDbConnection" connectionString="Server=127.0.0.1; Database=HMS; Integrated Security=false; User Id=sa; password=root" providerName="System.Data.Odbc "/>
C#
string query = "...";
OdbcConnection msSQLConnection = new OdbcConnection(strConnection);
OdbcCommand command = new OdbcCommand(query, msSQLConnection);
command.Connection.Open();
I tried using the below and it's ok. Any idea how I can get ODBC to work?
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLDbConnection"].ToString()))
{
SqlCommand cmd = new SqlCommand("SELECT COMPANY_ID from COMPANY", cn);
cn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
rdr.Read();
}
SQL Connection and ODBC Connection do not use the same connection strings. For the ODBC connection you need to specify the driver.
For SQL Server 2012:
Driver={SQL Server Native Client 11.0};Server=127.0.0.1;Database=HMS;Uid=sa;Pwd=root;
You should use something like this :
DRIVER={MySQL ODBC 3.51 Driver}; SERVER=127.0.0.1; DATABASE=HMS; USER=sa; PASSWORD=root;
Then take a look in here :OBDC example
and then in here : Connection strings

Connecting C# Windows Form Application to Sql Server

I'm connecting my windows form application to SQL server but I get this error "SqlException was unhandled" when I start the program.
Here is my code:
void ShowEmployees()
{
using (SqlConnection Connect = new SqlConnection("Data Source=(local);" + "Database='SanMarDryCleaners';" + "Integrated Security=SSPI;"))
{
string strEmployees = "SELECT * FROM employees;";
SqlCommand cmdEmployees = new SqlCommand(strEmployees, Connect);
SqlDataAdapter daEmployees = new SqlDataAdapter();
daEmployees.SelectCommand = cmdEmployees;
DataSet dsEmployees = new DataSet("EmployeesSet");
daEmployees.Fill(dsEmployees);
Connect.Open();
dgvEmployees.DataSource = dsEmployees;
dgvEmployees.DataMember = dsEmployees.Tables[0].TableName;
}
}
Here is the screenshot:
The error suggest that it can't find the SQL Server. And that makes sense because you are using a SqlConnection class which is for Microsoft SQL Server only. You have to use MySQL libary.
Download it from this site:
http://dev.mysql.com/downloads/connector/net/
The error points to a problem while connecting to the server.
A SqlConnection is for SQL-Servers. Use a library specific to MySQL and a MySqlConnection.
See:
Connector/Net Installation
MySQL Connector/Net connection strings

connect to MySQL webserver with C#

I try to connect to a MySQL database on a server a friend of mine has created, but it still says it cannot connect to the server!
Here is my code:
String connectionString = "Persist Security Info=False;database=qwertyui;server=www.qwertyuiop.com;Uid=asdfghj;Pwd=qazwsxedc;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO etc.... ");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue( etc.... );
connection.Open();
int r = cmd.ExecuteNonQuery();
}
It failes on the connection.Open() instruction throwing an exception -> cannot connect to the server.
Any ideas please?
SqlConnection is a SQL Server client.
You need to download a MySql client from NuGet.
First download the MySQL Connector.
Make sure you add a reference to the DLL (+ set copy local to true !)
Add using MySql.Data.MySqlClient; on top of your class.
As for the Connection String, do not add http or www in front of server. As it will try to connect to apache (port 80) instead to MySQL. The default port of MySQL is 3306.
string connectionString = "Persist Security Info=False;database=qwertyui;server=qwertyuiop.com;Uid=asdfghj;Pwd=qazwsxedc;port=3306";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
string query = "INSERT INTO table VALUES (#parameter)";
connection.Open();
using (MySqlCommand cmd = new MySqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("#parameter", parameter);
cmd.ExecuteNonQuery();
}
}
If this is not working. Make sure MySQL allows remote access, if this is not the case, you can keep trying forever without any result.
First thing that comes to mind is that you will have to use a MysqlConnection and command.
http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlconnection.html
Is it a local database?
And if with all of above does not work try to get grant to all privileges(GRANT Syntax)!
Basically it will go something like:
GRANT ALL PRIVILEGES ON DBname.* to 'username'#'IPadress' IDENTIFIED BY 'password';

ConnectionString for SQL Server

I have xampp installed in my computer. I am trying to access data with ADO.Net. The connection string I am using is given below:
string connectionString = "Server = localhost; Database = magento; User Id = magento; Password = abcd;";
SqlConnection con = new SqlConnection(connectionString);
string cmdString = "SELECT date_added,title,description,url FROM adminnotification_inbox";
SqlDataAdapter da = new SqlDataAdapter(cmdString, con);
ds = new DataSet();
da.Fill(ds,"prog");
dt = ds.Tables["prog"];
currRec = -1;
totalRec = dt.Rows.Count;
button3.Enabled = true;
I am able to log in with the above user id and password in phpmyadmin, but cannot access the database with the above connection string. please help. Thanks in advance.
MySQL has its own ADO.NET connector: http://dev.mysql.com/downloads/connector/net/6.6.html#downloads
If you use that, you can create a MySqlConnection: http://dev.mysql.com/doc/refman/5.5/en/connector-net-tutorials-intro.html
The basic SqlConnection is used for Microsoft's own SQL Server products.
9-22-14 - Hope others see this if you don't:
You need a driver in your connect string I believe. "MySQL ODBC 3.51 Driver" is the Window's driver name.
string connectionString ="Driver={MySQL ODBC 3.51 Driver}; SERVER= .... ok put the rest of your connect string here.
Note: this is the string to connect to a MySQL db using MS Access VBA:
Dan

Cannot connect to database by custom code using the same connection string the sqldatasource uses

I can't find the mistake in my code below.When I use SQLDataSource to connect my database,there's no error.However,if I try to write the custom code to connect the database using the same connection string SQLDataSource uses,I encounter this error:
(provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I suppose there's no mistake in my code,but in the configuration settings of SQL 2008 Express.
Thanks in advance...
SqlConnection sqlcon = new SqlConnection();
sqlcon.ConnectionString = "Data Source=ERHANEMREEROGLU/SQLEXPRESS;Initial Catalog=KET;Integrated Security=True";
sqlcon.Open();
SqlCommand sqlcmd = new SqlCommand();
sqlcmd.Connection=sqlcon;
sqlcmd.CommandText = "SELECT * FROM Login";
sqlcmd.CommandType = CommandType.Text;
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
Shouldn't this read:
sqlcon.ConnectionString = "Data Source=ERHANEMREEROGLU\\SQLEXPRESS;Initial Catalog=KET;Integrated Security=True";
There problem is in the statement in sqlcmd.ExecuteNonQuery();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Login", sqlcmd))
DataTable t = new DataTable();
adapter.Fill(t);
Actualy you are executing a query and you need either SqlDataReader or SqlDataAdapter here.
Try to check if your SQL server allows remote connections, you can set that in the sql server configuration manager
and then enable the remote TCP connection
You should change your line from:
sqlcmd.ExecuteNonQuery();
to:
SqlDataReader dr = sqlcmd.ExecuteReader();
If you are using Windows Authentication on your SQL database you may need to change the Integrated Security to SSPI? Although I'm not overly sure. - edit reading some information about this and SSPI is equivalent to True, so see suggestions below instead.
sqlcon.ConnectionString = "Data Source=ERHANEMREEROGLU/SQLEXPRESS;Initial Catalog=KET;Integrated Security=SSPI";
But as John Blade said you may also need to check in the Configuration Manager that it accepts remote connections.
Also make sure you've added the Windows user to the database. You can do this by using the SQL Mangement Studio Tools.
You are executing ExecuteNonQuery(); which is for Insert/update/delete statements. You may fill a DataReader using ExecuteReader or a dataset/datatable using SQLDataAdapter.
SqlDataReader reader = sqlcmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0]));
}
You can try:
using (SqlConnection sqlcon = new SqlConnection(
"Data Source=ERHANEMREEROGLU\\SQLEXPRESS;Initial Catalog=KET;Integrated Security=True"))
{
sqlcon.Open();
using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM Login", sqlcon ))
{
DataTable t = new DataTable();
a.Fill(t);
}
}

Categories

Resources