Whats wrong with my connection string? - c#

Hello please help me out with this connection string and even my procedure properties are attached
try
{
conn = new SqlConnection("Server=RM-MOBL\MSSQLSERVER1;DataBase=master;Trusted_Connection=True;");
conn.Open();
SqlCommand cmd = new SqlCommand("dbo.new", conn);
cmd.CommandType = CommandType.StoredProcedure;
rdr = cmd.ExecuteReader();
Console.WriteLine(" connection success");
}
// I hope I have mentioned correct connection string but
// not able to execute my stored procedure
i am facing error
![please see error here ][3]

The above code might not be a best way to Connect the database.
In your web.config add these lines which will connect to your database inside <configuration> section
<connectionStrings >
<add name="myConnectionString" connectionString="Server=ServerName;Database=DatabaseName;User ID=UserId;Password=Password;Trusted_Connection=False;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
And in your C# file add these references
using System.Data.SqlClient;
using System.Web.Configuration;
Inside Public Class add this Connection
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
Now you can open the Connection by having con.Open();

Try this,if you are using local machine
SqlConnection con = new SqlConnection("Server=RANJITHM-OBL\MSSQLSERVER1;initial catalog=master;integrated security=true");
SqlCommand cmd = new SqlCommand("dbo.new", conn);
cmd.CommandType = CommandType.StoredProcedure;
if (con.State == ConnectionState.Closed)
con.Open();
rdr = cmd.ExecuteReader();
Console.WriteLine(" connection success");

Related

Error 1042 has occurred: Connect Timeout expired

I am trying to connect to the SQL server with the below connection string but it is giving this "error Connect Timeout expired"
I have tried to telnet and it connected successfully. However, from the code, I cannot connect even though I have tried to specify the default port.
Is there anything am doing wrong? Thank you in advance.
string _connectionString = #"Server=myIP,1433;Database=myDB;User Id=myID;Password=myPass;";
using (MySqlConnection con = new MySqlConnection(_connectionString))
{
con.Open();
string sqlQuery = "SELECT * FROM Inventory";
using (MySqlCommand cmd = new MySqlCommand(sqlQuery, con))
{
MySqlDataReader result = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (result.Read())
{
}
con.Close();
}
}
Telnet result
Use backslash if you have an instance of your SQL Server "Server=myIP\sqlexpress".
If the server is your local machine, use Windows Authentication instead:
"Server= localhost; Database= myDB; Integrated Security=True;"
Or you can use App.Config to configure your SQL connection`, this is how I configure mine using Windows Authentication, not username and password. First, add an App.config to your application. Then add this:
<connectionStrings>
<add name="SqlConnectionString" connectionString="Data Source=localhost;Initial Catalog=myDB;Integrated Security=true"/>
</connectionStrings>
And on your program:
string _connectionString = string connString = ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString;
using (con = new SqlConnection(_connectionString))
{
string sqlQuery = "SELECT * FROM Inventory";
SqlCommand cmd = new SqlCommand(sqlQuery, con)
con.Open();
SqlDataReader result = cmd.ExecuteReader();
while (result.Read())
{
}
con.Close();
}
Don't forget to add using directive:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

Unable to insert values in sql server local db using c#

I'm unable to insert data into table. we are using local db. I'm not even getting any exception
string constr = ConfigurationManager.ConnectionStrings["server"].ConnectionString;
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("insert into Client_Name(Name) values('" + textBox1.Text + "')",con);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ee)
{
Console.Write("Exception");
}
}
In app.config
<connectionStrings>
<add name="server" connectionString="Data Source = (LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\msm.mdf;Integrated
Security=True;Connect Timeout=30" providerName="System.Data.SqlClient" />
</connectionStrings>
I have tried all the possible way, and got the best solution considering your scenario.
During an hour observation got to know due database connection
persistence issue you were having that problem try below snippet would
work as expected.
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\msm.mdf;Connect Timeout=30;Integrated Security=True;";
using (var _connection = new SqlConnection(connectionString))
{
_connection.Open();
using (SqlCommand command = new SqlCommand("Insert into [LocalTestTable] values (#name,#description)", _connection))
{
command.Parameters.AddWithValue("#name", "TestFlatName");
command.Parameters.AddWithValue("#description", "TestFlatDescription");
SqlDataReader sqlDataReader = command.ExecuteReader();
sqlDataReader.Close();
}
_connection.Close();
}
Hope that will resolve your problem without having anymore issue.

How do inject from Asp.net to a SQL database?

I have a hard time figuring out what is wrong about my code. The purpose is to take data from a registering form in ASP to my user data columns in my SQL database.
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
try
{
string cmd = "insert into UserLogin
values(#UserName,#Password)";
SqlConnection cnn = new SqlConnection(cmd);
SqlCommand cmd2 = new SqlCommand(cmd, cnn);
cmd2.Parameters.AddWithValue("#UserName", UsernameBox.Text);
cmd2.Parameters.AddWithValue("#Password", PasswordBox.Text);
cnn.Open();
cmd2.ExecuteNonQuery();
You're using the connection string in the connection variable but the variable you're passing to SqlCommand is cnn which doesn't have a valid connection string associated with it.
I've cleaned up your code and made use of using block to ensure the correct manner of disposing the object. Please see below:
string connectionString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (var con = new SqlConnection(connectionString))
{
string query = "insert into UserLogin values(#UserName, #Password)";
using (var cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#UserName", UsernameBox.Text);
cmd.Parameters.AddWithValue("#Password", PasswordBox.Text);
con.Open();
cmd.ExecuteNonQuery();
}
}
You have two SqlConnection variable and assigning wrong one in the SqlCommand. The working code will be:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
try
{
string cmd = "insert into UserLogin values(#UserName, #Password)";
SqlCommand cmd2 = new SqlCommand(cmd, connection);
cmd2.Parameters.AddWithValue("#UserName", UsernameBox.Text);
cmd2.Parameters.AddWithValue("#Password", PasswordBox.Text);
cnn.Open();
cmd2.ExecuteNonQuery();

How to get SQL Server Name Using Windows Authetication in C#

I am trying to fetch the Server Name using C# for that I am trying blow mentioned code.
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
con = new SqlConnection("Data Source=.;Database=Master;Integrated Security=SSPI");
con.Open();
cmd = new SqlCommand("select * from sysservers where srvproduct='SQL Server'", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
ServerCollection.Add(dr[2].ToString());
}
dr.Close();
it's give me Exception like Login faild for user Dhaval.patel so can anyone please help how to connect using window's Authetication in C#.
Try to Put Integrated Security = true like this
con = new SqlConnection("Data Source=.;Database=Master; Integrated Security=true");
It should be like :-
("Server= localhost; Database=Master;Integrated Security=SSPI, Integrated Security=True");
If you have a named instance of SQL Server, you'll need to add that as well,
e.g.,
"Server=localhost\sqlexpress"

How to insert record into a sql server express database table?

I'm trying to insert a textbox value to a database table called site_list.
The site_list table contains two columns id and site_name, id set to auto increment
This is the code I'm trying and when it execute there is no error, but the data is not showing up in the table
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|scraper_db.mdf;";
SqlCommand addSite = new SqlCommand("INSERT INTO site_list (site_name) "
+ " VALUES (#site_name)", conn);
addSite.Parameters.Add("#site_name", SqlDbType.NVarChar).Value = textBox1.Text;
conn.Open();
addSite.ExecuteNonQuery();
conn.Close();
Any help would be appreciated.
Regards
Edit:
This code started to work
string connstring = "Data Source=.\\SQLExpress;"+
"Integrated Security=true;"+
"User Instance=true;"+
"AttachDBFilename=|DataDirectory|scraper_db.mdf;"+
"Initial Catalog=scraper_db";
using (SqlConnection connection = new SqlConnection(connstring))
{
connection.Open();
SqlCommand addSite = new SqlCommand("INSERT INTO site_list (site_name)"+
"VALUES (#site_name)", connection);
addSite.Parameters.AddWithValue("#site_name", textBox1.Text);
addSite.ExecuteNonQuery();
connection.Close();
}
as people suggests, try creating the database on the server (it will be even easier to handle using Sql Management Studio).
Once that's done, try the following (just tested and it works):
using (SqlConnection conn = new SqlConnection(#"Persist Security Info=False;Integrated Security=true;Initial Catalog=myTestDb;server=(local)"))
{
SqlCommand addSite = new SqlCommand(#"INSERT INTO site_list (site_name) VALUES (#site_name)", conn);
addSite.Parameters.AddWithValue("#site_name", "mywebsitename");
addSite.Connection.Open();
addSite.ExecuteNonQuery();
addSite.Connection.Close();
}
try
{
using (SqlConnection conn = new SqlConnection(#"Persist Security Info=False;Integrated Security=true;Initial Catalog=myTestDb;server=(local)\SQLEXPRESS;database=Inventory;Data Source=localhost\SQLEXPRESS;"))
{
SqlCommand addSite = new SqlCommand(#"INSERT INTO Creation (Name,Product,Quantity,Category) VALUES (#Name,#Product,#Quantity,#Category)", conn);
addSite.Parameters.AddWithValue("#Name", textBox1.Text);
addSite.Parameters.AddWithValue("#Product", textBox2.Text);
addSite.Parameters.AddWithValue("#Quantity", textBox3.Text.ToString());
addSite.Parameters.AddWithValue("#Category", textBox4.Text);
thisConnection.Open();
addSite.ExecuteNonQuery();
}
}
catch
{
thisConnection.Close();
}
try this out :
string sql = String.Format("INSERT INTO site_list (site_name) VALUES('{0}')", myTextBox.Text);
using(SqlConnection connection = new SqlConnection(myConnectionString))
{
connection.open();
using(SqlCommand cmd = new SqlCommand(sql, connection))
{
cmd.ExecuteNonQuery();
}
}
Good luck
Try storing your textbox value in a variable. As in:
#stringname = textbox1.text
addSite.Parameters.Add("#site_name", SqlDbType.NVarChar).Value = #stringname;
(IMPORTANT! the # in #stringname is not necessary, but protects you against hackers!)
This code has worked wonders for me.
My apologies. The answer I gave previously will not work because the variable name used in the insert command (in your case #site_name) must match the variables used in your sqlcommand. As in:
#site_name = textbox1.text
addSite.Parameters.Add("#site_name", SqlDbType.NVarChar).Value = textBox1.Text;
Sorry for the confusion I might have caused.

Categories

Resources