using System;
using System.Data.OleDb;
using System.Diagnostics;
namespace PullData
{
class Program
{
static void Main(string[] args)
{
OleDbConnection connLocal = new OleDbConnection("Provider=SAOLEDB.10;Data Source=dental;Persist Security Info=True;User ID=dba;PWD=sql;Location=1.2.3.4");
OleDbCommand cmdLocal = new OleDbCommand("SELECT tran_num, amount, tran_date FROM transactions", connLocal);
try
{
connLocal.Open();
}catch (Exception connerr) { Debug.WriteLine(connerr.Message);}
OleDbDataReader readLocal = cmdLocal.ExecuteReader();
while (readLocal.Read())
{
Console.WriteLine(readLocal.GetString(0), readLocal.GetString(1), readLocal.GetString(2));
}
readLocal.Close();
connLocal.Close();
if (Debugger.IsAttached)
{
Console.ReadLine();
}
}
Above is the code I am attempting to run in Visual Studio 2015, I'm trying to connect to an old SQL Anywhere 10 DB, the connection string is directly from VS2015's Database Explorer that is connected and viewing tables (with the exception of my adding the PWD). This is just a stepping stone to view the table contents so I can later have the query written to a CSV or text.
The error I'm receiving when attempting to debug/run is:
An unhandled exception of type 'System.InvalidCastException' occurred in System.Data.dll
Additional information: Specified cast is not valid.
Which points to:
Console.WriteLine(readLocal.GetString(0), readLocal.GetString(1), readLocal.GetString(2));
Seems like it's not recognizing the reader. Anyone have any advice? Thanks!
Related
I'm writing an application using C# and System.Data.SQLite (the library from https://system.data.sqlite.org) and I feel like I'm beating my head against a wall. My unit tests on my larger chunks of code are randomly throwing exceptions, so in preparation for asking a question here, I started a new project with as small a chunk of code as I can. This chunk of code, which creates a new sqlite file and then adds a table to it, keeps throwing a Database is not open error whenever it attempts to add the table.
Looking at the similar questions on Stack Overflow, many of them are regarding using SQLite with Android, which is not the case here.
In my research, I've seen that I want to keep the connection open only for as long as I need it, but as you can see from the code sample, I'm using using to isolate the connection and command right next to each other, but I'm still having problems.
There's probably something obvious I'm doing wrong, but I'm at a loss to figure out what it is.
Thanks!
using System.Data.SQLite;
namespace SmallCode {
class Program {
private const string DB_NAME = "Test.sqlite";
private const string DB_CONN_STRING = "Data Source=" + DB_NAME + ";Version=3;";
static void Main(string[] args) {
Program p = new Program();
SQLiteConnection.CreateFile(DB_NAME);
using (SQLiteConnection c = new SQLiteConnection(DB_CONN_STRING)) {
string sqlCreateTableAccount = "CREATE TABLE ACCOUNT (ID INTEGER PRIMARY KEY, NAME TEXT NOT NULL);";
using (SQLiteCommand cmd = new SQLiteCommand(sqlCreateTableAccount, c)) {
// EXCEPTION THROWN ON NEXT LINE
cmd.ExecuteNonQuery();
}
}
}
}
}
You still need to .Open the connection...
using (SQLiteConnection c = new SQLiteConnection(DB_CONN_STRING)) {
c.Open(); //<------ ADD THIS LINE
string sqlCreateTableAccount = "CREATE TABLE ACCOUNT (ID INTEGER PRIMARY KEY, NAME TEXT NOT NULL);";
using (SQLiteCommand cmd = new SQLiteCommand(sqlCreateTableAccount, c)) {
// EXCEPTION THROWN ON NEXT LINE
cmd.ExecuteNonQuery();
}
}
Creating the connection with using doesn't automatically open the connection, it just creates it. You don't need to explicitly .Close() it at the end though, it will be closed when the using disposes it.
I am trying to write a very simple C# Script that establishes a connection to my Azure SQL Database.
using System;
using System.Data.SqlClient;
namespace first_project
{
class MainClass
{
public static void Main(string[] args)
{
var cb = new SqlConnectionStringBuilder();
cb.DataSource = "server.bloo.blah.foobar";
cb.UserID = "user#database";
cb.Password = "secret";
cb.InitialCatalog = "database";
using (SqlConnection connection = new SqlConnection(cb.ConnectionString))
{
try
{
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
}
From what I have gathered online, this code should be working? However, I am getting the following error
System.AggregateException: One or more errors occurred. ---> System.IO.IOException: Unable to read data from the transport connection: Operation on non-blocking socket would block. ---> System.Net.Sockets.SocketException: Operation on non-blocking socket would block
Could anyone enlighten me on what is going on? Thanks in advance.
First the SQL database has a firewall. You have to add your IP through the azure portal.
Secondly make sure your connection string is correct you can look at another sample online. I remember having syntax errors as well, just copy the string that azure gives you.
In your connection, instead of
cb.UserID = "user#database"
use
cb.UserID = "user"
That should work.
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?
I just started to use SQLite. Doesn't seem to look like MySQL and SQL Server and MS Access that I use. I sought for several information online, nothing I could really find as well I decided to post here.
It connects well, and the libraries are present in the folder, but when I try to insert into the database, it throws an exception to the console.
My code looks like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data.SQLite;
namespace sqliteInsert
{
class Program
{
static void Main(string[] args)
{
string constring = "Data Source=C:\\Users\\DornellPC\\Desktop\\people_db.db;Version=3;New=False;Compress=True;";
using (SQLiteConnection con = new SQLiteConnection(constring))
{
try
{
string sql = "insert into people_data (first_name,last_name,tel,email) values ('Jack','Darwin','0966358936','j_darwin#fsmail.net')";
con.Open();
Console.WriteLine("Connection open!");
using (SQLiteCommand cmd = new SQLiteCommand(sql,con))
{
cmd.ExecuteNonQuery();
Console.WriteLine("Success!");
Console.ReadLine();
}
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
}
and no information has been inserted into the database as it throws this exception:
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or ass embly 'System.Data.SQLite, Version=1.0.105.2, Culture=neutral, PublicKeyToken=db 937bc2d44ff139' or one of its dependencies. The system cannot find the file specified.
at sqliteInsert.Program.Main(String[] args)
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;")