SqlConnection string - c#

I am trying to make a portable connection string with a service-based database.
If I use
C:\Users\X\Desktop\C# Projects\Windows Form Applications\PortableConnectionString\PortableConnectionString\BazaDate.mdf
and not |DataDirectory|BazaDate.mdf, it works.
What can I do to make it portable?
SqlConnection conn= new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\BazaDate.mdf;Integrated Security=True;");
conn.Open();

Environment.GetCommandLineArgs()[0] is the full path of your executable, thus:
string appPath = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
string connStr = $#"Data Source=(LocalDB)\v11.0;AttachDbFilename={appPath}\BazaDate.mdf;Integrated Security=True;";
var conn = new SqlConnection(connStr);
conn.Open();

Related

use SqlConnection, but can not find the SQL database

My database layout looks like this:
-App_Data
-Database.mdf
-Database_log.ldf
and this is my code:
string strConn = "Data Source=.\\SQLEXPRESS;Initial Catalog=Database;Integrated Security=True;";
SqlConnection myConn = new SqlConnection(strConn);
myConn.Open();
String strSQL = "INSERT INTO dbo.member (Id, Password, Name, Jobtitle,level,phone) VALUES ('a01', '123', 'bobo', 'Tester','1','010919')";
SqlCommand myCommand = new SqlCommand(strSQL, myConn);
myConn.Close();
When I test in browser, however, it sends an error message and stops in this code "myConn.Open();"can't find server
Why is this happening?
change
string strConn = "Data Source=.\\SQLEXPRESS;Initial Catalog=Database;Integrated Security=True;";
to
string strConn = #"Data Source=.\SQLExpress;Initial Catalog=Database;Integrated Security=True";
Attach a database file, located in the data directory, on connect to a
local SQL Server Express instance
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|dbfilename.mdf;Database=dbname;
Trusted_Connection=Yes;
so your connection string should be similar to below, replace database name corectly
string strConn =#"Server=.\SQLExpress;AttachDbFilename=|DataDirectory|Database.mdf;Database=dbname; Trusted_Connection=Yes;";
using (SqlConnection myConn = new SqlConnection(strConn))
{
string strSQL = "INSERT INTO dbo.member (Id, Password, Name, Jobtitle,level,phone) VALUES ('a01', '123', 'bobo', 'Tester','1','010919')";
myConn.Open();
using(SqlCommand myCommand = new SqlCommand(strSQL, myConn))
{
myCommand.ExecuteNonQuery(); // you haven't execute the insert
}
}

Barcharts in C#

Here I created a barchart using a Windows application with C#. I retrieve the data from stored procedure and bind the with barchart. So far I wrote this code:
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=ARUN-PC/SQLEXPRESS;Initial Catalog=InsightPro_Latest ;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SumofPowders";
DataSet ds = new DataSet();
da.Fill(ds);
InsightPro_BarChart.DataSource = ds;
InsightPro_BarChart.DataBind();
con.Close();
}
catch
{
}
Now I faced the error: The ConnectionString property has not been initialized. I don't know where I did the mistake.
Can anyone please clarify my doubt in coding also? Thanks in advance.
Provide connection string to SqlConnection (otherwise it will not know which database connect to):
string connectionString = "Server=Name;Database=DbName;User=Foo;Password=Bar";
SqlConnection con = new SqlConnection(connectionString);
// you can also set connection string via property
// con.ConnectionString = connectionString;
Usually connection strings are stored in configuration file of your application in <connectionStrings> section (see Connection Strings and Configuration Files):
<connectionStrings>
<add name="myConnection"
connectionString="Server=Name;Database=DbName;User=Foo;Password=Bar"
providerName="System.Data.SqlClient"/>
</connectionStrings>
You can use ConfigurationManager to get connection string from config file (you should add reference to System.Configuration assembly):
string connectionString =
ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
You need add the connection string to you SQL.
For example:
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;";
Then do the needed SqlConnection as:
SqlConnection con = new SqlConnection(connectionString);
More on Connection strings: http://www.connectionstrings.com/sql-server-2005/
You can add your database connection details in the config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Test" connectionString="Data Source=.;Initial Catalog=OmidPayamak;IntegratedSecurity=True" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Once you have the configuration, you then need to access the same for your connection.
You can use ConfigurationManager:
using System;
using System.Configuration;
var connectionString = ConfigurationManager.ConnectionStrings["Test"];
Then use the SqlConnection to pass the connection and start off:
SqlConnection con = new SqlConnection(connectionString);
Try this
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword";
conn.Open();
Web.config
<connectionStrings>
<add name="ApplicationServices" connectionString="copy connection string here"
/>
</connectionStrings>
SqlCommand command = new SqlCommand();
command.CommandText = "SumofPowders";
command.CommandType = CommandType.StoredProcedure;
con.open();
SqlDataAdapter da = new SqlDataAdapter(command,con);
DataSet ds = new DataSet();
da.Fill(ds);
InsightPro_BarChart.DataSource = ds;
InsightPro_BarChart.DataBind();
add a connection string to your webconfig inside ConnectionString tag
<add name="constr" connectionString="Data Source=ARUN-PC/SQLEXPRESS;Initial Catalog=InsightPro_Latest ;User ID= YourServersername ;Password=YourServerPassword" providerName="System.Data.SqlClient"/>
in your code behind
string conn = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection con = new SqlConnection(conn);

Error while converting string to SqlConnection

I'm getting this error:
Cannot implicitly convert type string to System.Data.SqlClient.SqlConnection
Here is my C# code.
protected void Button1_Click(object sender, EventArgs e)
{
//login button
SqlConnection sqlConn = "Your Conncetion String"; //The error is here
sqlConn.Open();
SqlCommand sqlComm = new SqlCommand();
sqlComm.CommandText = String.Format("select * from users where userName=#userName and password=#password");
sqlComm.Parameters.AddWithValue("#userName", TextBox1.Text.Trim());
sqlComm.Parameters.AddWithValue("#password", TextBox2.Text.Trim());
sqlComm.CommandType = CommandType.Text;
sqlComm.Connection = sqlConn;
SqlDataReader sqlRead = sqlComm.ExecuteReader();
if (sqlRead.Read())
{
Session["username"] = sqlRead["username"];
}
// SqlRead.Close();
//sqlConn1.Close();
Response.Redirect("Default.aspx");
}
Can someone explain what this error means and how to fix it?
I understand you have a connection string and want a SqlConnection object. You can use one of its constructors:
string connString = "Your Conncetion String"; // valid connection string
var sqlConn = new SqlConnection(connString);
It will be best if you use using keyword as this will take care of closing the connection properly. You should also use using for your SqlReader.
using (var sqlConn = new SqlConnection(connString))
{
sqlConn.Open();
// the rest of the code
}
Change
SqlConnection sqlConn = "Your Conncetion String";
To
SqlConnection sqlConn = new SqlConnection("Your Conncetion String");
it should be
SqlConnection sqlConn = new SqlConnection("Your Conncetion String");
You can read it from web.config
SqlConnection sqlConn = new
SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
now this error The name 'ConfigurationManager' does not exist in the current context
You have to add a reference to the System.Configuration.dll
then add using System.Configuration; to your class.
You can now access your config file like this:
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

SQL query is not being executed in C#

I have a SQL query and I want to execute it in C# on a button click, but when I click the
button the database is not being affected:
private void button1_Click(object sender, EventArgs e) {
String ConnectionString = "Data Source=localhost;Initial Catalog=mydb;Integrated Security=True";
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.CommandText = "INSERT INTO MedTab (MedID,MedName,Manf,MedProd,MedExp,TimeLeft,InStock) VALUES (4,'sdfs','sdfsd','sdfsdf','sdfsdf','sdfsd',33);";
con.Close();
}
The code you want is this:
String ConnectionString = "Data Source=localhost;Initial Catalog=mydb;Integrated Security=True";
String sql = "INSERT INTO MedTab (MedID,MedName,Manf,MedProd,MedExp,TimeLeft,InStock) VALUES (4,'sdfs','sdfsd','sdfsdf','sdfsdf','sdfsd',33);";
using (SqlConnection con = new SqlConnection(ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(sql, con))
cmd.ExecuteNonQuery();
}
Add cmd.ExecuteNonQuery after setting the command text.
You need to actually execute the query (try ExecuteNonQuery).
You're currently opening a connection, setting the statement to execute, then just closing the connection.

Inserting into database from textbox in C# using parameters

I am a newbie to c#. I am trying to insert the values from the text box into the table in my database.
Table Name : address
Fields : name(varchar(50)),
age(int),
city(nchar(10))
When i try to retrieve the values from the database it is working perfectly.
Here is my code. Please help me rectify it.
string s = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
SqlConnection a = new SqlConnection(s);
a.Open();
SqlCommand comm = new SqlCommand("INSERT INTO [address](name,age,city) VALUES(#na,#ag,#ci)");
string na = textBox1.Text;
int ag = int.Parse(textBox2.Text);
string ci = textBox3.Text;
comm.Parameters.Add("#na", System.Data.SqlDbType.VarChar,50).Value = na;
comm.Parameters.Add("#ag", System.Data.SqlDbType.Int).Value = ag;
comm.Parameters.Add("#ci", System.Data.SqlDbType.NChar,10).Value = ci;
comm.Connection = a;
comm.ExecuteNonQuery();
MessageBox.Show("okay");
a.Close();
The values are not reflected in the database.
try with this code :
string connectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand insertCommand = connection.CreateCommand())
{
insertCommand.CommandText = "INSERT INTO address(name,age,city) VALUES (#na,#ag,#ci)";
insertCommand.Parameters.Add("#na", na);
insertCommand.Parameters.Add("#ag", ag);
insertCommand.Parameters.Add("#ci", ci);
insertCommand.Connection.Open();
insertCommand.ExecuteNonQuery();
}
}

Categories

Resources