This question already has answers here:
How to connect to LocalDb
(12 answers)
Closed 1 year ago.
class ContactsRepository : IContactsRepository
{
private string connectionString = "Data Source=(LocalDB);Initial Catalog=Contact_DB;User ID=****;Password=**********";
public bool Delete(int ContactID)
{
throw new NotImplementedException();
}
public DataTable SelectAll()
{
string query = "Select * From MyContacts";
SqlConnection connection = new SqlConnection(connectionString);
Sql command = new SqlCommand(query, connection);
DataTable data = new DataTable();
adapter.Fill(data);
return data;
}
}
I get this error:
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: SQL Network Interfaces, error: 51 - An instance name was not specified while connecting to a Local Database Runtime. Specify an instance name in the format (localdb)\instance_name.
https://www.connectionstrings.com/sql-server-2017/
Check here for correct connection string
and also you need "connection.Open()" before run command
public class PullDataTest
{
// your data table
private DataTable dataTable = new DataTable();
public PullDataTest()
{
}
// your method to pull data from database to datatable
public void PullData()
{
string connString = #"your connection string here";
string query = "select * from table";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dataTable);
conn.Close();
da.Dispose();
}
}
Related
Here is my code
public class LoginFunction
{
public DataTable User (string username, string pword)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(ConnectionHelper.CnnVal("GymDB")))
{
var query = ("Select * from [USER] where username = '{username}' and password = '{pword}'");
SqlDataAdapter sda = new SqlDataAdapter(query, connection);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
}
}
}
}
The error im getting is "cannot convert from 'System.Data.IDbConnection' to 'string'".
The error is with the connection argument for SqlDataAdapter - I thought this would get the SQL connection from the IDbConnection.
I'm sorry I can not comment yet.
Try to change IDbConnection to SqlConnection and var query to string query and take away the parenthesis.
See if it works!?
I wrote a C# program to output the contents what is contained in database tables, but when I append conn.open(), dialog box doesn't be created although there isn't any compile error. I already checked whether or not the setting of database information such as ip address, user name, pass word, and database name, but there isn't any misses. I wonder why it isn't executed as soon as appending conn.open():
public static string constring = "Data Source= 192.168.0.21; User=root; Password=admin;database=hwg;";
SqlConnection conn = new SqlConnection();
private string strConnString = "";
[public void ConnectDB]
strConnString = constring;
if (conn.State.ToString().Equals("Closed"))
{
conn.ConnectionString = strConnString;
conn.Open(); //problem on this line
if (conn.State == ConnectionState.Open)
{
}
else
{
conn.Close();
}
}
[public DataTable GetDBTable(string sql)]
SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
[public Form1()]
InitializeComponent();
db = new Con_database();
db.ConnectDB();
[private void button1_Click(object sender, EventArgs e)]/*If we click button1, the overall contents of applied table in database hwg is listed*/
string sql = "SELECT * FROM id_repository";
DataTable dt = db.GetDBTable(sql);
DatabaseInquiry.DataSource = dt;
db.ClosedDB();
I think you need to define USERID instead of USER in your connection string.
Old connection string:
public static string constring
= "Data Source= 192.168.0.21; User=root; Password=admin;database=hwg;";
New connection string:
public static string constring =
"Data Source= 192.168.0.21;Initial Catalog="your database name"; UserID=root; Password=admin;";
I'm creating a social Networking Website for that I used "Social Networking Website in ASP.NET - Open Source" from
http://www.c-sharpcorner.com/UploadFile/rahul4_saxena/social-networking-website-in-Asp-Net-open-source-project/
When I tried to run the project on my Visual Studio 2012 edition it is showing error like below,
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)
Source Error:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
/// <summary>
/// Summary description for DataBaseClass
/// </summary>
public class DataBaseClass
{
SqlDataAdapter da;
SqlConnection con;
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
public DataBaseClass()
{
//
// TODO: Add constructor logic here
//
}
public void ConnectDataBaseToInsert(string Query)
{
con = new SqlConnection(#"Data Source=Veena-SQLServer2008; Initial Catalog=RNetworkingWebApplication;");
cmd.CommandText = Query;
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
public DataSet ConnectDataBaseReturnDS(string Query)
{
ds = new DataSet();
con = new SqlConnection(#"Data Source=Veena-SQLServer2008; Initial Catalog=RNetworkingWebApplication;");
cmd.CommandText = Query;
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return ds;
}
public DataTable ConnectDataBaseReturnDT(string Query)
{
dt = new DataTable();
con = new SqlConnection(#"Data Source=Veena-SQLServer2008; Initial Catalog=RNetworkingWebApplication;");
cmd.CommandText = Query;
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return dt;
}
}
Visual studio pointing the error here da.Fill(dt).
I have spent 2 days to debug this error but still I couldn't. Please help me.
It is very simple. Your code is not able to connect to the database. Open Server Explorer in Visual Studio and connect to your database to confirm you are able to connect. And then get your connection string right.
And you do have a database, right?
Im Trying to connect to a database on a SQL server Located on 192.168.100.42\DEV but i keep getting a network related error see below by code and then the error , If any one can help it would be appreciated
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString = "Data Source=192.168.100.42\Dev;Initial Catalog=UNIS;User ID=sa;Password=Password1!";
using (SqlCommand scmd = new SqlCommand("dbo.searchName"))
{
scmd.CommandType = CommandType.StoredProcedure;
scmd.Parameters.Add(new SqlParameter("#name", cbUserName.Text));
SqlConnection conn = new SqlConnection(connectionString);
SqlDataAdapter dataAdapter = new SqlDataAdapter(scmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
conn.Open();
scmd.Connection = conn;
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView2.ReadOnly = true;
dataGridView2.DataSource = ds.Tables[0];
conn.Close();
}
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)
I have a problem with the following code. Please help.
What I am trying to do is pass a sqlcommand to a function which then returns a dataset.
The function 'Get data' takes sqlcommand as a parameter. This function is in class 'DatabaseUtilities'
//Initializing sql connection
static SqlConnection _Connection = new SqlConnection("Data Source=(local);Initial Catalog=db_Test;Integrated Security=True");
//Connection property
public static SqlConnection Connection
{
get {return _Connection;}
}
//The class that takes sqlcommand as parameter
public static DataSet GetData(SqlCommand Command)
{
_Connection.Open();
SqlDataAdapter Adapter = new SqlDataAdapter();
Adapter.SelectCommand = Command;
DataSet Table = new DataSet();
Adapter.Fill(Table);
_Connection.Close();
return Table;
}
This is how sqlcommand is passed into the above function. This function is from a different class.
public DataSet GetLogByDate(string SearchValue)
{
Command.CommandType = CommandType.StoredProcedure;
Command.Connection = DatabaseUtilities.Connection;
Command.CommandText = "sp_GetLogByDate";
Command.Parameters.AddWithValue("#LogDate", SearchValue);
return GetData(Command);
}
This code throws the fllowing error.
Invalid object name 'sp_GetLogByDate'.
I do have the above stored procedure in my database. I have no idea why this happened. Could anyone help?
You have to connect Command with Connection:
//The class that takes sqlcommand as parameter
public static DataSet GetData(SqlCommand Command)
{
Command.Connection = _Connection;