I've created a local SQL Server database and Login form, Here is the code of Login form :
namespace WindowsFormsApplication1
{
public partial class LoginForm : Form
{
public LoginForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (!(Usertxt.Text == string.Empty))
{
SqlConnection connection = new SqlConnection(#"Data Source=|DataDirectory|\crimemanagement.sdf");
connection.Open();
SqlCommand cmd = new SqlCommand(#"SELECT Count(*) FROM Login_table
WHERE Username=#Username and
Password=#Password", connection);
cmd.Parameters.AddWithValue("#Username", Usertxt.Text);
cmd.Parameters.AddWithValue("#Password", Passtxt.Text);
int result = (int)cmd.ExecuteScalar();
if (result > 0)
{
MessageBox.Show("Login Success");
}
else
{
MessageBox.Show("Incorrect login");
}
}
else if (Passtxt.Text == string.Empty || Usertxt.Text == string.Empty)
{
MessageBox.Show("Enter Username and Password");
}
}
}
}
But when I try to login using the form which I created it give me a connection error and highlights connection.open();
System.Data.SqlClient.SqlException was unhandled
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: 26 - Error Locating Server/Instance Specified)
In order to work with SQL Server Compact database files in ADO.NET you need to use the System.Data.SqlServerCe.dll ADO.NET provider, and use objects like SqlCeConnection, SqlCeCommand etc.
You're using SqlConnection which is for proper SQL Server (the server-based system), but you're referencing a SQL Server CE data file (.sdf).
If you want to use the .sdf, you need to use SqlCeConnection, SqlCeCommand etc. - not the SqlConnection and SqlCommand
Related
I got a linux server with mariadb installed and i want to send queries to that server with C# with this script
namespace SQLTEST
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
CreateCommand(
"INSERT INTO TEST(name) VALUES ('sample');",
"server=IPadress;database=test;uid=root;password=**;pooling=false;" );
Console.ReadKey(true);
}
private static void CreateCommand(string queryString, string connectionString)
{
try{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
System.Console.WriteLine("Connectin open");
command.ExecuteNonQuery();
}
} catch(Exception e){
System.Console.WriteLine(e.Message);
}
}
}
}
I tried to change the connection string multiple times. It seems like i cant get over the command.connection.open line
This is the error i keep getting
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)
You have MariaDB (essentially MySQL) as your database and you are trying to use Microsoft SQLServer client libraries to access it. It'll never work - they are completely different databases.
Use MySQL library instead
I have a pivot table using windows form application
I want to replace the data in pivot table with import data using .sql
I have tried this code
private void btnSelectFile_ItemClick(object sender,DevExpress.XtraBars.ItemClickEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Text files | *.sql";
if (dlg.ShowDialog() == DialogResult.OK)
{
string fileName;
fileName = dlg.FileName;
}
string ConnString = "server=localhost; user id=root; password=; database=db;persist security info=true;";
DataTable Data = new DataTable();
using(SqlConnection connect = new SqlConnection(ConnString))
{
connect.Open();
SqlCommand cmd = new SqlCommand(#"SELECT * FROM [dataGridView1_Data$]", connect);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(Data);
connect.Close();
}
}
but the connection 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)'
Start by connecting to the database from visual studio directly. Your connection string looks incorrect.
string ConnString = "server=localhost; user id=root; password=; database=db;persist security info=true;";
I do not believe SQL Server allows empty passwords anymore.
Actually, i wanted to check is my connection string valid.
There are asp.net mvc web app and mysql db deployed on azure, so i want use second thing in first. So, i added db to visual studio server explorer - db and all tables are visible.
Now i tried to add connectionstring to my project, and, wow, there are two of them i found:
First: In Visual studio data connection properties:
server=us-cdbr-azure-central-a.cloudapp.net;user id=userid;persistsecurityinfo=True;database=crawlerdb
Second: In azure workplace's database property:
Database=CrawlerDB;Data Source=us-cdbr-azure-central-a.cloudapp.net;User Id=userid;Password=userpass
And both of them doesn't work. Never lucky.
Connection state checking code:
using (SqlConnection conn = new SqlConnection(connstr))
{
try
{
conn.Open();
var q = conn.State;
}
catch(Exception ex)
{
var q = ex.Message;
}
}
What am i doing wrong?:) Tell me plz:)
public class CrawledDataContext : DbContext
{
public CrawledDataContext()
{
Database.SetInitializer<CrawledDataContext>(null);
using (SqlConnection conn = new SqlConnection("server=us-cdbr-azure-central-a.cloudapp.net;user id=bb15193d20f901;persistsecurityinfo=True;database=crawlerdb"))
{
try
{
conn.Open();
var q = conn.State;
}
catch(Exception ex)
{
var q = ex.Message;
}
}
}
public DbSet<GroupInfo> GroupInfoes { get; set; }
}
Here is exception message:
"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 for SQL Server Databases. you should use MySqlConnection instead.
using (MySqlConnection conn = new MySqlConnection("server..."){}
I am trying to retrieve data from a database with the following code:
public partial class populate : System.Web.UI.Page
{
SqlConnection scon = new SqlConnection("Data Source = localhost; Integrated Security = true; Initial Catalog = populate");
protected void Page_Load(object sender, EventArgs e) {
StringBuilder htmlString = new StringBuilder();
if(!IsPostBack)
{
using (SqlCommand scmd = new SqlCommand())
{
scmd.Connection = scon;
scmd.CommandType = CommandType.Text;
scmd.CommandText = "SELECT * FROM populate";
scon.Open();
SqlDataReader articleReader = scmd.ExecuteReader();
htmlString.Append("'Populate page:'");
if (articleReader.HasRows)
{
while (articleReader.Read())
{
htmlString.Append(articleReader["dateTime"]);
htmlString.Append(articleReader["firstName"]);
htmlString.Append(articleReader["lastName"]);
htmlString.Append(articleReader["address"]);
htmlString.Append(articleReader["details"]);
}
populatePlaceHolder.Controls.Add(new Literal { Text = htmlString.ToString() });
articleReader.Close();
articleReader.Dispose();
}
}
}
}
}
It's throwing an error:
The system cannot find the file specified
I am wondering if someone can show me where the error is or guide me through debugging this. Thanks in advance.
(update): More specifically, the scon.Open() is causing the error:
Message=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)
This looks easy enough to fix, but I'm not very good with the database. Any help will be appreciated.
I don't know what SQL Server edition you have installed, and what you called it (as an instance name) .....
Go to Start > SQL Server > Configuration Tools > Configuration Manager; under SQL Server Services, search for the SQL Server service - what is it's name??
If it's SQL Server (SQLEXPRESS), then that means you have the Express edition, with an instance name of SQLEXPRESS - change your connection string to:
Data Source=.\SQLEXPRESS;Initial Catalog=populate;Integrated Security=true;
If it's SQL Server (MSSQLSERVER) then you should be fine really - you have an unnamed, default instance ....
I am trying to read a table from a Wampserver using this, but I get an error message "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)"
When I ping localhost all the pings are received. Is this code correct?
private void button5_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("user id=root;" +
"password=pass;server=localhost;" +
"database=database; " +
"connection timeout=10");
string query = "select * from table";
SqlCommand cmd = new SqlCommand(query, myConnection);
myConnection.Open(); // the error
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(tabelsql);
myConnection.Close();
da.Dispose();
}
If you're using a WampServer than that means you're using MySQL, right?
MySQL and SQL Server are not the same. SQLConnection, SQLCommand and SQLDataAdapter are used to connect to SQL Server (the RDBMS from Microsoft), not MySQL.
To access a MySQL database from .NET you can use the MySQL Connector.
SqlCommand and SqlDataAdapter are part of the MS SQL ADO.NET native client and can only be used for MS Sql Server. WAMP appears to include MySql. For that, you'll likely want to use the MySql ADO.NET driver found here. And this article provides some sample code for reading MySql data utilizing a DataReader.
To Read a single table from MySql database which is in wamp server.
If wamp-server is in localhost then,
Add reference ..
using MySql.Data.MySqlClient;
And after this..
write below public partial class this connection query..
MySqlConnection cn = new
MySqlConnection
("server=localhost;database=database;userid=root;password=;charsetutf8;");
write this GetData() in your form load event or below InitializeComponent...
private void GetData()
{
cn.Open();
MySqlDataAdapter adp = new MySqlDataAdapter("SELECT * from
tablename", cn);
DataTable dt = new DataTable();
adp.Fill(dt);
dataGridViewName.DataSource = dt;
adp.Dispose();
cn.Close();
}