I am trying to connect to an SQL db to extract data and I am using Dapper for the process. I assume I am having some problems with the connection string; I am trying to access a remote sql server 2012 db but my connection keeps failing:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data.SqlClient;
namespace Data_Connection
{
public static class Program
{
static void Main(string[] args)
{
string connetionString = null;
SqlConnection cnn ;
connetionString = "Server=datanet.local.net/datadb; Database=ddata;Trusted_Connection=True";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
Console.WriteLine("Connection Open !");
cnn.Close();
}
catch (Exception ex)
{
Console.WriteLine("Can not open connection !");
}
}
}
}
I have never tried connecting to an sql db using c# and I am fairly new to the environment. Any help would be appreciated
Thanks!
Related
I am going to create a database with SQL Server in C#, and also make basic queries.
And I wrote the following code to create the database.
Where can I find my database?
I downloaded SSMS but I am not sure how to check it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace MakeBusDB
{
class Program
{
static void Main(string[] args)
{
string query;
SqlConnection sqlConn = new SqlConnection("Server=localhost;Integrated security=SSPI;database=master");
query = "DROP DATABASE IF EXISTS Session1DB";
SqlCommand sqlCommand = new SqlCommand(query, sqlConn);
try
{
sqlConn.Open();
sqlCommand.ExecuteNonQuery();
query = "CREATE DATABASE Session1DB";
sqlCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
Console.ReadLine();
}
}
}
enter image description here
I am trying to create a project that will read, write,and check for duplicates in my access data base file. I am using C# and keep getting "Connection failed error that I have written into the program if the connection state = 0. If anyone can offer any help I would appreciate it. I am using Access 2016 and I am not sure what references I need for my project (if any). Everything I have found online is either outdated or doesn't work.
Thank you!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.IO;
using System.Data.OleDb;
namespace RHG
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
using (OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.16.0;Data Source=C:\Users\grosales\Documents\rhg\RHG\Used.accdb"))
{
try
{
connection.Open();
MessageBox.Show("connected");
}
catch (Exception ex)
{
MessageBox.Show("connection failed");
}
}
}
`
You have not opened the connection.
connection.Open();
Note: Checking the connection state is not enough. You might get an exception when trying to open the connection. Enclose it in try-catch instead.
It is also a good practice to enclose work on a connection with using
using (var connection = new OleDbConnection()) {
connection.ConnectionString =
#"Provider=Microsoft.ACE.OLEDB.16.0;Data Source=C:\Users\...\Used.accdb";
try {
connection.Open();
//TODO: do something with the connection
} catch (Exception ex) {
MessageBox.Show("Connection Failed\r\n\r\n" + ex.Message);
}
}
This ensures that the connection will be closed and the resources be released.
Try following the examples here: https://msdn.microsoft.com/en-us/library/system.data.oledb.oledbconnection(v=vs.110).aspx
You're missing the connection.Open(); statement, which should be wrapped in a try catch.
Additionally, you can specify the connection string within the constructor, like
using (OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.16.0;Data Source=C:\Users\grosales\Documents\rhg\RHG\Used.accdb"))
{
//do DB access here
}
//no need to call connection.Close() - it's automatically done once you leave the using block.
Okay, I'm trying to make a simple project for school, in which the teacher is letting us use the root user so we connect to databases everything. But while compiling, there seems to be an error in my class I use to connect to MySql:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;
namespace BuscarDatos
{
class ClaseConectar
{
public static MySqlConnection obtener_conexion()
{
MySqlConnectionStringBuilder c = new MySqlConnectionStringBuilder();
c.Server = "localhost";
c.UserID = "root";
c.Password = "*******"; //password
c.Database = "proyecto_almacen"; //my database name already created
MySqlConnection con = new MySqlConnection();
con.Open();
return con;
}
}
}
I keep getting this error:
MySql.Data.MySqlClient.MySqlException: 'Authentication to host '' for user '' using method 'mysql_native_password' failed with message: Access denied for user ''#'xxxxxxxxxx' (using password: NO)'
Also, I changed it to MySqlConnection since I got an error before in another class, about how I couldn't convert MySql into Sql only. Here's an example of the class I changed it for:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
namespace BuscarDatos
{
class Agregar
{
public static int AddName (string pNombre,string pAp_paterno, string pAp_materno, string pMatricula,
string pDireccion, string pTelefono)
{
int resultado = 0;
MySqlConnection con = ClaseConectar.obtener_conexion();
MySqlCommand Comando = new MySqlCommand(string.Format("Insert into maestros (nombre, ap_paterno, ap_materno, matricula," +
"direccion, telefono) values('{0}','{1}','{2}','{3}','{4}','{5}')", pNombre, pAp_paterno, pAp_materno,
pMatricula, pDireccion, pTelefono), con);
resultado = Comando.ExecuteNonQuery();
con.Close();
return resultado;
}
}
}
You're not giving the connection any connection string. It doesn't know what to open.
When you create the MysqlConnectionStringBuilder it is completely separate from the MySqlConnection you create. You must use them together:
MySqlConnection con = new MySqlConnection(c.ConnectionString);
This way you're actually giving the generated connection string to the connection object.
I've been trying to make a connection with my SQL Server database (Mynewdatabase) using the default connection string that was generated (supposedly) when I added the data source for this project. However, I'm thus far unable to make a connection: I'm getting an error that "the server was not found or was not accessible".
This my code. Thanks so much for any help you can offer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace Parsevcf2sql
{
class Program
{
static void Main(string[] args)
{
// here is where I get what I believe is an appropriate connection string
string cs = Parsevcf2sql.Properties.Settings.Default.MynewdatabaseConnectionString;
SqlConnection myconnection = new SqlConnection(cs);
Console.WriteLine(cs);
try
{
myconnection.Open();
Console.WriteLine("This worked!");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
This might help you out, change localhost to your address and database name as well.. But Please check sql server must be in running mode
{
// connection string!
SqlConnection myConn = new SqlConnection("Server=localhost\\SQLEXPRESS;Integrated security=SSPI;database=Mynewdatabase;");
try
{
myConn.Open();
Console.WriteLine(myConn );
}
catch (System.Exception)
{
// some exception
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
myConn.Dispose();
}
}
or check out this tutorial
I have installed the MySQL server using XAMMP.Created a new database with some data using phpmyadmin.Then i tried to connect to database using this code.But it did not connect.It shows me an error.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Testing!");
SqlConnection myco = new SqlConnection("server=localhost;User Id=root;database=customer;Trusted_Connection=yes");
try
{
myco.Open();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.ReadKey();
}
}
}
Error:
http://pastebin.com/MyEtk4w6
You have MySql then you need to use the classes for MySql not the ones used for SqlServer
MySqlConnection myco = new MySqlConnection("Server=localhost;Database=customer;" +
"Uid=username;Pwd=password;");
Also the connection string for MySql is different
Server=localhost;Database=customer;Uid=username;Pwd=password;
The connection strings for MySql could be very numerous, you should check the correct one for your requirement here at connectionstrings.com
It's because you're using a SqlConnection object which is for Microsoft SQL Server.
Use a MySQLConnection instead.