Cannot create the SqlConnection Object in C#? - c#

I'm writing a simple program to access one local database, yet it says: the type or namespace name sqlconnect could not be found
error message:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: 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)
anyone have an idea about that? Thanks
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace SQL_Server_Connect_Test
{
class Program
{
static void Main(string[] args)
{
//using (SqlConnection connection = new SqlConnection("integrated security=SSPI;data source=Bo_Test_Database; persist security info=False; initial catalog=T_User"))
{
SqlConnection con = new SqlConnection("Data Source=.; Initial Catalog=Bob_Test_Database; User ID=sa; Password=t123456");
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "";
cmd.ExecuteNonQuery();
}
con.Close();
con.Dispose();
}
Console.WriteLine("hehe");
}
}
}
I enabled the sa account and the password is valid
the database is on local
db name = Bob_Test_Database, the table's name is dbo.T_User

Try creating your connection string using a udl file.
After you get the udl file to sucessfully connect to the DB, simply open it using notepad and copy the connection text to your application.

I don't see any sqlconnect in your code. Anyway, try this:
SqlConnection con = new SqlConnection("Data Source=T_User;
Initial Catalog=Bob_Test_Database;
Persist Security Info=True;")

Related

I am trying to create dynamic table into existing database in SQL-Server by using C#.NET console Application. But i getting exception

here is exception
An unhandled exception of type 'System.Data.SqlClient.SqlException occurred in System.Data.dll
Additional information:
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)
my code is here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace AdoDemo
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.CreateTable();
}
public void CreateTable()
{
SqlConnection con = null;
con = new SqlConnection("data source=.; database=MYDB; integrated security=SSPI");
SqlCommand cmd = new SqlCommand("create table STUDENT(ID int,SNAME varchar(10),MOBILE
bigint)",con);
con.Open();
cmd.ExecuteNonQuery();
Console.WriteLine("Table created successfully..");
con.Close();
}
}
}
This is myCode Snippet
You need to fix the connection string:
con = new SqlConnection("data source=.; database=MYDB; integrated security=SSPI")
You need something like that:
Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;
User ID=myDomain\myUsername;Password=myPassword;
You have missed: Data Source, User ID and Password

Windows Form "An unhandled exception of type 'System.ArgumentException' occurred in System.Data.dll" [duplicate]

This question already has answers here:
ASP.NET use SqlConnection connect MySQL
(3 answers)
Closed 5 years ago.
I'm in C# language and still learning about Model View Control. Now I have project for my school to make a cashier application, but I have this error when I'm trying to connect mysql database.
The error is :
An unhandled exception of type 'System.ArgumentException' occurred in System.Data.dll
Additional information: Keyword not supported: 'port'.
this is my codes :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
namespace AppKasir.KoneksiDB
{
class KoneksiBarang
{
public static SqlConnection getKoneksiBarang()
{
string strCon = "SERVER = localhost; PORT = 3306; UID = root; PWD = ; Database = db_kasirmysql;";
return new SqlConnection(strCon);
}
}
}
The error is at line:
return new SqlConnection(strCon);
Which the symbol ; is underline red.
System.Data.SqlClient.SqlConnection represents an open connection to a SQL Server database.
Try this if you want to access a MySQL database:
How to connect to MySQL Database?

Error when opening an sql connection: 'MyConnection.ServerVersion' threw an exception of type 'System.InvalidOperationException'

I have seen this problem in many posts, but cannot fix.. I'm trying to connect to a table in my SQL DB, using visual Studio 2015 (C#), and keep on getting an error.
This is my code (note: the connection string was taken from appsettings.json file):
string ConnectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=aspnet5-LicenseTool-b66aeae7-0f53-4987-8e86-6fba8a7f5e16;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
using (SqlConnection MyConnection = new SqlConnection(ConnectionString))
{
// some code here
}
...
when I run I get an error of:
'MyConnection.ServerVersion' threw an exception of type
'System.InvalidOperationException'
See attachments of error and of server data - You can see I'm connected and I have correct parameters.
Error Message
Server
Your error message clearly states Invalid operation. The connection is closed.. This means that you didn't Open() the connection.
Use this:
string ConnectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=aspnet5-LicenseTool-b66aeae7-0f53-4987-8e86-6fba8a7f5e16;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
using (SqlConnection MyConnection = new SqlConnection(ConnectionString))
{
MyConnection.Open();
// some code here
}

Database Connectivity with oracle database using c#

While trying to connect the oracle database I am getting the following error
"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)"}
Problem may be silly one but this is my first time with database so need help:
My code is:
static void Main(string[] args)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Data Source=ORCL_BOA; database=BOANEWDOC;User Id=BOANEWDOC;Password=BOANEWDOC;Trusted_Connection=true";
conn.Open();
//code
}
you may need to reference Oracle.ManagedDataAccess.dll on ODTwithODAC121012.zip you can download from oracle site.
do not use System.Data.OracleClient as it is obsolete.
var connection = new OracleConnection(YourConnectionString);
try
{
connection.Open();
//AMK: Do some stuff with the db
}
catch (Exception exception)
{
//AMK: do some other stuff in case of error
}
finally
{
if(connection !=null && connection.State==ConnectionState.Open)
connection.Close();
}

C# console application Invalid Operation Exception

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Sql;
using System.Data.SqlClient;
namespace BissUpdater
{
class Program
{
static void Main(string[] args)
{
string connectionString = "Data Source=H....;
Initial Catalog=LANDesk; Persist Security Info=True;
User ID=Mainstc; Password=xxxxxxxx";
SqlConnection con = new SqlConnection(connectionString);
con.Open();
}
}
}
The SQL Connection threw a invalid operation exception.
"Invalid Operation. The connection is closed".
This is my complete Code. In a other program, it works perfect.
That is the second time, that doesnt work. Im working with VS2005...maybe my program is damaged?
Stacktrace:
at System.Data.SqlClient.SqlConnection.GetOpenConnection()
at
System.Data.SqlClient.SqlConnection.get_ServerVersion()
The correct way doing that should be something like:
static void Main(string[] args) {
string connectionString = "Data Source=H....;
Initial Catalog=LANDesk;User ID=Mainstc; Password=xxxxxxxx";
// removed Persist Security Info=True;
using(SqlConnection con = new SqlConnection(connectionString))
{
if (con.State==ConnectionState.Closed)
{
con.Open();
}
}
}
Using Using Statement it will automatically dispose your SQL connection.
Check this also: Best Practices for Using ADO.NET on MSDN
Other things to do: Use SQL Management Studio and try to use your sql authentication login credential from your connection string and if you have successfully connected to your database using that account the above code should work for you.
Best Regards
The code should read
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
...
}
Try add this code. You probably has open connection and while rerun program you try to again open connection or you have problem with server or your connection string
con.Close();
See there for more info http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open.aspx
you can check connection state before opening ittry this :
SqlConnection con = new SqlConnection(connectionString);
if (con.State==ConnectionState.Closed)
{
con.Open();
}
// here your code goes for sql operations
con.Close();
Try to use using statements. Direct manually opening and closing data bases in case of large databases is bad idea.
using(SqlConnection con = new SqlConnection(connectionString))
Try to do like this for open and close connections>>
public DB(string conStr):base()
{
con = new OracleConnection(conStr);
con.Open();
}
public void Close()
{
con.Close();
//con.Dispose();
}
Hope Helpful.
I was having same problem, my solution in VB is:
Dim db As New Database
' ... Some Work with EF without procedures (90 seconds)
db.SaveChanges()
For Each p In list
If db.Database.Connection.State <> ConnectionState.Open Then
' This is only executed 1 time
db.Database.Connection.Open()
End If
' ... Some Work with EF but calling a mapped procedure (1 or 2 seconds each call)
db.MyProcedure(p.FieldId)
Next
db.Dispose()
But the total time was 200 seconds, so I had to change this in my WebConfig of my WebService:
<system.web>
<httpRuntime executionTimeout="600" /> <!--10 min-->
...

Categories