I want to connect to SQL Server 2016 using Windows authentication.
I am using C# with this connection string
Server=192.168.1.12,14331;Database=master;Integrated Security=true;Timeout=30
or
Server=serversql\newinstance;Database=master;Integrated Security=true;Timeout=30
The error is a timeout connection.
When using connection with SQL Server authentication like this:
Server=192.168.1.12,14331;Database=master;User Id=***;Password=****;Timeout=30
everything is ok.
Source code C#
var constr = "<connection string>";
using (var connection = new SqlConnection(constr))
{
var command = connection.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = "SELECT 1";
command.CommandTimeout = 0;
connection.Open();
command.ExecuteNonQuery();
}
But when I am using SQL Server Management Studio to check connection to the SQL Server instance with Windows authentication, it is ok. Using alias or Ip address does not help the error.
I don't understand why I get this error ...
Help me please! Thanks you everyone!
UPDATE:
If I use connection 1 with IP and port, there is an error:
Login failed. The login is from an untrusted domain and cannot be used
with Windows
UPDATE:
Instance SQL installed on other PC the same network LAN with My PC.
I'm checked Log Viewer on PC install instance SQL but no record log.
I'm not sure it works for you, but you can try it:
SqlConnection cnn;
public connect(){
string strConnect = #"Data Source=192.168.1.12,14331;Network Library=DBMSSOCN;Initial Catalog=master;User ID=****;Password=*****";
cnn = new SqlConnection(strConnect);
try
{
cnn.Open();
}
catch(Exception)
{
// connect failed
}
}
public void ExeQuery(string query){
// query="select * from tblA"
SqlCommand sqlCmd = new SqlCommand(query,cnn);
sqlCmd.ExecuteNonQuery();
sql.Dispose();
}
Related
I am new to msql and i am working on MySQL Workbench 8.0 CE
I am trying to bind data from database to datagridview as show below but i am getting error below
but I am able to connecto my database using MySQL Workbench 8.0 CE so the connection to up so what I can do ?
public void GetPersonData()
{
string connstr = "Server=localhost;Database=newsequesterdb;Uid=reser;Pwd=00";
string query = "SELECT * FROM NEWSEQUESTERDB.PERSON;";
using (SqlConnection conn = new SqlConnection(connstr))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(query, conn))
{
DataSet ds = new DataSet();
adapter.Fill(ds);
dgv_data.DataSource = ds.Tables[0];
}
}
}
error message
System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
SqlConnection is specific to MS SQL Server. Use MySqlConnection (and associated command and data adapter classes) instead.
Note that MySqlConnection is not built in to the .NET Framework - you'll need to install it separately.
The thing is that you cannot use an SqlConnection instance nor SqlAdapter, those are intended to be SQL Server connection classes. And this you can see by the exception itself.
...(provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
So, what's next? You should really look up to this question and may solve a few doubts.
From that question we can see that is using other references to connect to MySQL. Specifically Oracle's nugget package: MySQL.Data
using MySql.Data;
using MySql.Data.MySqlClient;
From that question example:
var dbCon = DBConnection.Instance();
dbCon.DatabaseName = "YourDatabase";
if (dbCon.IsConnect())
{
//suppose col0 and col1 are defined as VARCHAR in the DB
string query = "SELECT col0,col1 FROM YourTable";
var cmd = new MySqlCommand(query, dbCon.Connection);
var reader = cmd.ExecuteReader();
while(reader.Read())
{
string someStringFromColumnZero = reader.GetString(0);
string someStringFromColumnOne = reader.GetString(1);
Console.WriteLine(someStringFromColumnZero + "," + someStringFromColumnOne);
}
dbCon.Close();
}
I'm using Sql Server 2017 and Visual Studio 2017. I transferred my database from my PC to my friend's laptop using Generate Scripts. I use the following code in my friend's laptop when trying to connect to said database in the laptop:
using (SqlConnection sqlCon = new SqlConnection(#"Data Source = (local); Initial Catalog = PresentasiDB; Integrated Security = True; Trusted_Connection = True;"))
{
DataTable orderTable = new DataTable();
SqlDataAdapter sqlda;
string insertOrder = "INSERT INTO \"Order\" DEFAULT VALUES";
using (SqlCommand newOrder = new SqlCommand(insertOrder, sqlCon))
{
sqlCon.Open();
newOrder.ExecuteNonQuery();
}
sqlda = new SqlDataAdapter("SELECT TOP 1 * FROM \"Order\" ORDER BY OrderID DESC", sqlCon);
sqlda.Fill(orderTable);
orderID = Convert.ToInt32(orderTable.Rows[0][0]);
}
However, this failed. The failure occurred in the sqlCon.Open() part. I've tried using SQL Server login Authentication and Windows Authentication. Both failed. Someone, please help me.
In the data source you need to specify server name you use to connect to sql server.
As shown in the screen the datasource here is "gaurav.goel
Try your connecting string something like this (for sa login)
string connstr = userid=sa;password=sapassword;server=localhost,1433;database=PresentasiDB;Trusted_Connection=no
To test it did you try entering the server as 'localhost' from management studio?
i have a problem with making a local database into my c# project and creating it..
I tried first with making a Microsoft Sql Server but the problem is that i need to make app which should run on every pc. The app should input data from user , and collect it to the database, and on every start of program, the database should be filled with the leftover of earlier input.. What you suggest me to do?
First to connect your c# application with sqlite you should start with getting connection string
private static string executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private static string oldconnectionstring = Path.Combine(executableLocation, "YourDB.db");
private static string connectionString = "Data Source =" + oldconnectionstring.ToString();
After getting connection, to add your input to database follow below steps
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
//Open connection to DB
conn.Open();
//Query to be fired
string sql = "Your Query to insert rows";
//Executing the query
using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
{
//Executing the query
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
//Close connection to DB
conn.Close();
}
I'm working on Windows CE application, I was trying to connect to server database from the device and fetch some information from db on button click, below is the code I tried,
SqlConnection conn = new SqlConnection("Data Source=192.168.0.0;Initial Catalog=DashReport;Integrated Security=SSPI; User ID=SA;Password=Admin#123;");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT STORE, YEAR,DATE FROM TOPSALES WHERE MONTH = " + txtcode.Text + ";";
// cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
conn.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
gvDataGrid.DataSource = dt;
}
else
{
MessageBox.Show("No data found");
}
}
conn.Close();
but while running the application I'm getting a SqlException. It seems there is something wrong with the connection string. What is the right method to do it?
You cannot have both the integrated security and specify a specific user id and password at the same time. Since you have the Integrated Security=SSPI;, that will take precedence and your connection tries to connect with the currently logged in Windows user.
Most likely, from a Windows CE device, you want to use the specific User I
string connStr = "Data Source=192.168.0.0;Initial Catalog=DashReport;User ID=SA;Password=Admin#123;"
SqlConnection conn = new SqlConnection(connStr);
And another word of caution from long time SQL Server users, admins, and programmers: you should NEVER EVER use the built-in sa account! Just don't do it - use another account (possibly one you create specifically for this application).
Have you tried using the Server Explorer of Visual Studio, then connect to the database, get the Connection String via Properties Window, and use it as your connection string?
Just some kind of assurance that your connection to the database is the same as your code.
I am trying to connect to SQL Server 2012 express. There is a database called employee which I would like to save data from a WPF form to a table called [dbo].[EVUSERS]. It is stored in my local Database. From some examples I see that "Data Source=.\SQLEXPRESS" Is this correct? Or should I specify the table aswell? using localhost as the server doesn't work either.
I get an error saying "the server was not found or was not accessible."
Do I have to configure the server in some way to receive connections?
Here is my attempt.
void saveData()
{
try
{
var firstName = fNameTextbox.Text;
var lastName = LNameTextBox.Text;
var userName = UserName.Text;
String pass = PasswordTextBox.Password;
String confirm = ConfirmTextBox.Password;
int loggedIn = 1;
//parameterise values
string connectionString = #"Data Source=.\SQLEXPRESS;Database=Employee";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO [dbo].[EVUSERS] (UName, Pass, FName, LName, Attempts, LastLogin, LoggedIn) VALUES (#UName, #Pass, #FName, #LName, #Attempts, #LastLogin, #LoggedIn)";
command.Parameters.AddWithValue("#UName", UserName);
command.Parameters.AddWithValue("#Pass", pass);
command.Parameters.AddWithValue("#FName", firstName);
command.Parameters.AddWithValue("#LName", lastName);
command.Parameters.AddWithValue("#Attempts", attempts);
command.Parameters.AddWithValue("#LastLogin", lastLogIn);
command.Parameters.AddWithValue("#LoggedIn", loggedIn);
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("command number of rows = " + command);
}
//connection.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Here is a screenshot of the server connection.
Many Thanks
.\SQLExpress is correct. If the database name is correct (although for SQL Express it should be a path to the file, yes?) then you can add ";Integrated Security=SSPI" to the connection string and you'll be OK if you are the user who installed it.
Can Use It For Connect With Sql Server 2012 :
var connectionString = "Server=127.0.0.1;DataBase=Employee;
User Id=(sa or your user id without Parenthesis);
Password=(your password without Parenthesis);";