Can't able to connect to Database - c#

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.

Related

Error when trying to connect to access database in C# for project

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.

Code using wrong namespace

I having an aspx.cs file that I am adding code to. I have all the right namespaces and references in my solution, but my code is referencing the wrong namespace with the following error on my Server server = new Server()
System.Web.UI is a 'property' but used as a 'type'
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.IO;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace IISLoggingSolution
{
public partial class Main : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//connection string for SQL DB
string connectionString = #"Data Source=Computer\SQLEXPRESS;Initial Catalog=IISLogs;Integrated Security=True";
//Location of the query to be ran
string script = File.ReadAllText(#"C:\\Users\\User\\Desktop\\query.txt");
SqlConnection conn = new SqlConnection(connectionString);
//this is the error line
Server server = new Server(new ServerConnection(conn));
//executes query
server.ConnectionContext.ExecuteNonQuery(script);
}
}
}
How can I get it to use the Microsoft.SqlServer.Management.Smo instead of trying to used the System.Web.UI?
using NS_Server = Microsoft.SqlServer.Management.Common;
using System.Web.UI;
...
NS_Server.Server server = new NS_Server.Server();
the line using NS_Server is an alias. You can use it as a shortcut when there are namespace collisions.
You can use an alias directive:
using Server = Microsoft.SqlServer.Management...Server;
It may not work if property takes precedence, but in that cas you can simply specify the full namespade path.
var server = new Microsoft.SqlServer.Management....Server();

How to connect to oracle using Oracle.ManagedDataAccess

I am trying to connect to oracle data base using below code.
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.Types;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string connectionString =
"Data Source=a;User Id=id;Password=pwd;";
OracleConnection con = new OracleConnection(connectionString);
con.Open();
Console.WriteLine("Connected to Oracle Database {0}", con.ServerVersion);
con.Dispose();
Console.WriteLine("Press RETURN to exit.");
Console.ReadLine();
}
}
}
Its throwing exception saying:
An unhandled exception of type
'Oracle.ManagedDataAccess.Client.OracleException' occurred in
Oracle.ManagedDataAccess.dll
Additional information: ORA-12514: TNS:listener does not currently
know of service requested in connect descriptor.
Can any body correct me what was going wrong with the above code?
the issues maybe is the connection string, if you haven't TNS name "a" registered
you can try this
string connectionString =
"Data Source=localhost:1521/xe;User Id=USERDB;Password=pwd";
by default XE is name for oracleservice
where
Data Source -> localhost:1521/xe (ip:port/servicename)
User Id -> you Oracle user
Password -> you Oracle password

Connection Strings and Dapper

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!

How do I use C# queries on a prexisting database(SQLite database)?

I have run into a problem where my C# code is creating a whole new database instead of using a preexisting one. Then my program runs into errors where the program cannot find the table to insert the information even though the preexisting database has the table because the code itself is looking at the new table. Here is my code:
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 Finisar.SQLite;
namespace WestSlope
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SQLiteConnection sqlite_conn;
SQLiteCommand sqlite_cmd;
//SQLiteDataAdapter sqlite_datareader;
sqlite_conn = new SQLiteConnection("DataSource=ClientLogDB.db;Version=3;New=True;Compress=True;");
//open conection
sqlite_conn.Open();
//create sql commands
sqlite_cmd = sqlite_conn.CreateCommand();
//Let SQLite command know query is known
sqlite_cmd.CommandText = "INSERT INTO ASAM (ASAMone, ASAMtwo, ASAMthree, ASAMfour, ASAMLim, ASAMLimEX) VALUES ('Had to call', 'Reffered', 'Had to call', 'Watched', 1 , 'Injured legs');"
;
//execute query
sqlite_cmd.ExecuteNonQuery();
sqlite_conn.Close();
}
}
}
What the code is supposed to do is when the user presses a button the program will save information to the preexisting database; but, as you can see the program is making a new database instead of using the preexisting one.
Use new=false in your connection string to use existing database file.
Following should be the connection string:
sqlite_conn = new SQLiteConnection("DataSource=ClientLogDB.db;Version=3;New=False;Compress=True;");

Categories

Resources