How to get SQL Server Name Using Windows Authetication in C# - 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"

Related

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();

Whats wrong with my connection string?

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");

About connecting sql server to c# (with ADO.NET)

I Have a problem in connecting my database to c# in connection string section
this is my code but when i run it , i get an error about this :
"Format of the initialization string does not conform to specification
starting at index 84"
My Code:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection Cn = new SqlConnection(#" Server=TheAddress ; Database=MyDataBase.mdf ; integrated security='True' #");
Cn.Open();
SqlCommand Cm = new SqlCommand("", Cn);
Cm.CommandText = "INSERT INTO Table1(ID_Food, Name_Food , TypeOfService_Food , Price_Food , Type_Food) VALUES (#ID_Food , #Name_Food , #TypeOfService_Food , #Price_Food , #Type_Food)";
Cm.Parameters.AddWithValue("#ID_Food", textBox1.Text);
Cm.Parameters.AddWithValue("#Name_Food", textBox2.Text);
Cm.Parameters.AddWithValue("#TypeOfService_Food", textBox3.Text);
Cm.Parameters.AddWithValue("#Price_Food", textBox4.Text);
Cm.Parameters.AddWithValue("#Type_Food", textBox5.Text);
Cm.ExecuteNonQuery();
Cn.Close();
}
I Cant Even Open My Connection (Error Happen in declaring SqlConnection)
I know its an Amature Question ... but its made me angry (i cant set it correctly)(with visual studio 2012 & sqlserver management studio 2012)
Looks like you have a "#" at the end you should remove from the connection string. You also might consider using the using statements when creating the SqlConnection and SqlCommand objects so they are properly disposed.
using (var Cn = new SqlConnection(#"Server=TheAddress;Database=MyDataBase.mdf;integrated security=True"))
{
Cn.Open();
using (var Cm = new SqlCommand("", Cn))
{
Cm.CommandText = "INSERT INTO Table1(ID_Food, Name_Food , TypeOfService_Food , Price_Food , Type_Food) VALUES (#ID_Food , #Name_Food , #TypeOfService_Food , #Price_Food , #Type_Food)";
Cm.Parameters.AddWithValue("#ID_Food", textBox1.Text);
Cm.Parameters.AddWithValue("#Name_Food", textBox2.Text);
Cm.Parameters.AddWithValue("#TypeOfService_Food", textBox3.Text);
Cm.Parameters.AddWithValue("#Price_Food", textBox4.Text);
Cm.Parameters.AddWithValue("#Type_Food", textBox5.Text);
Cm.ExecuteNonQuery();
Cn.Close();
}
}
you need to provide valid connection string .
Try This :
SqlConnection Cn = new SqlConnection(#"Data Source=TheAddress;Initial Catalog=MyDataBase.mdf;Integrated Security=True");
EDIT : from comments : as you are getting runtime excpetion please check wether you are able to communicate with the server or not.
Check this here

C# OleDbConnection con set to timeout

I have an app that queries an Access database and shows the data. I want the connection(con) to timeout after 2 minutes. Does anyone have any suggestions on how i can code this?
this is what i have in the beginning
OleDbConnection con;
OleDbDataReader dr;
OleDbCommand cmd;
con.Open();
cmd = new OleDbCommand(str, con);
dr = cmd.ExecuteReader();
Thank you
#Damith is close, but unfortunately the ConnectionTimeout property is read-only. You have to set the timeout in the connection string instead by using ... ;Connect Timeout=30;. Here's the documentation.
Don't share the connection, create the connection when you need and wrap it by using block,
if you need to set the timeout, you can set by using ConnectionTimeout property in connection string (e.g. ".....;Connect Timeout=30"
using (OleDbConnection con = new OleDbConnection(connectionString))
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
con.Open();
using (OleDbDataReader dr = cmd.ExecuteReader())
{
}
}
Did you try Timeout parameters,
OleDbCommand.CommandTimeout Property - When you need time out during execution of the query
OleDbConnection.ConnectionTimeout Property - When you need time out whilemaking a connection

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