How we can connect and fetch data from DataBase using DbConnection class - sql-server

How can I use DbConnection class to connect to a database (sql server or oracle) and fetch data from any table. I tried with following code, but i got a run time exception like this:
Error 3 error C2664:
'System::Data::SqlClient::SqlDataAdapter::SqlDataAdapter(System::String
__gc *,System::String __gc *)' : cannot convert parameter 2 from 'System::Data::Common::DbConnection __gc *' to 'System::String __gc *'
at new SqlDataAdapter(S"select * from [LabOpsStatus]",conn)
DbConnection *conn;
conn = new SqlConnection(S"Data Source=(local);Initial Catalog=myDb;User Id=user;Password=pw;");
conn->Open();
mySDataAdapter = new SqlDataAdapter(S"select * from [LabOpsStatus]",conn);
What is the wrong in this code?

Shaheer, you need to create the connection from a provider. I don't think my provider specified as Oracle is correct though.
some c# code again
DbProviderFactory factory = DbProviderFactories.GetFactory("Oracle");
DbConnection conn = factory.CreateConnection();
conn.ConnectionString = "Data Source=(local);Initial Catalog=myDb;User Id=user;Password=pw;";
DbCommand cmd = factory.CreateCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * from table1";

string datosConexion = "Data Source=(local);"
+ "Initial Catalog = myDb ; User Id=user;Password=pw;";
try
{
using (SqlConnection con = new SqlConnection(datosConexion))
{
con.Open();
string textoCmd = "select * from [LabOpsStatus]";
SqlCommand cmd = new SqlCommand(textoCmd, con);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}

Related

Conversion failed when converting from a character string to uniqueidentifier - Doesn't Rollback the transaction

The actual issue is not this - "Conversion failed when converting from a character string to uniqueidentifier" but the issue is that, the transaction doesn't get rolled back after you hit the issue.
My code here,
var connectionstring = "Server= ****; Database= ****; Integrated Security=True;";
var errorInformation = new List<string>();
using (SqlConnection objConn = new SqlConnection(connectionstring))
{
objConn.Open();
var objTrans = objConn.BeginTransaction(); // Begins here
var sql = $"insert into tblProject values('7', 'TestProject')";
SqlCommand insertCommand = new SqlCommand(sql, objConn, objTrans);
try
{
insertCommand.ExecuteNonQuery();
// ProjectID is a unique Identifier in database
SqlCommand cmd = new SqlCommand("SELECT * FROM SOMEOTHERTABLE WHERE PROJECTID=''", objConn, objTrans);
cmd.CommandType = CommandType.Text;
var dataTable = new DataTable("SomeTableName");
using (var adapter = new SqlDataAdapter(cmd))
{
var dt = adapter.Fill(dataTable); // Exception happens here
}
objTrans.Commit(); // Commit here
}
catch (Exception ex)
{
errorInformation.Add(ex.Message);
}
var sql1 = $"insert into tblProject values('8', 'TestProject')";
SqlCommand objCmd2 = new SqlCommand(sql1, objConn, objTrans);
objCmd2.ExecuteNonQuery();
if (errorInformation.Any())
{
objTrans.Rollback(); // Rollback here
}
}
The query that gets executed after the exception, using the same connection object will not rollback. This is a bug that Microsoft needs to look into. Otherwise their rollback feature is not reliable.
I would expect either my second insert command to fail or my rollback to be successful.

How to copy all schema from one database to other database (created at runtime)?

I have used schema for tables for one database,so how to copy all schema from one database to other database(database created at runtime)
string sql = "create database " + str1;
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
command.ExecuteNonQuery();
Response.Write("database created");
connection.Close();
string sqll = "(select * into " + str1 + ".cost_category.cost_category_info
from ERPAccounting.cost_category.cost_category_info where 1=2)
(select * into " + str1 + ".dbo.cost_centre_info from
ERPAccounting.cost_centre.cost_centre_info where 1=2)"
connection.Open();
SqlDataAdapter ad = new SqlDataAdapter(sqll, connection);
DataSet ds = new DataSet();
ad.Fill(ds);
Using C#, object DDL can be obtained by using SMO objects and then executed in the database where the objects need to be copied to. In the example below, references to Microsoft.SqlServer.Management.Smo, Microsoft.SqlServer.ConnectionInfo, Microsoft.SqlServer.Management.Sdk.Sfc, and System.Data.SqlClient are necessary. The DDL is first obtained from the SMO objects, then it used as the CommandText for the SqlCommand that is executed in the destination database. This example is for tables, but other objects (views, stored procedures, etc.) can also be copied using this method.
//set initial catalog to destination database
string connStr = #"Data Source=YourServer;Initial Catalog=DestinationDatabase;Integrated Security=SSPI;";
using (SqlConnection conn = new SqlConnection(connStr))
{
//set source server and database using SMO objects
Server srv = new Server(#"YourServer");
srv.ConnectionContext.LoginSecure = true;
srv.ConnectionContext.StatementTimeout = 600;
Database db = srv.Databases["SourceDatabase"];
//configure Scripter for DDL
Scripter script = new Scripter(srv);
ScriptingOptions scriptOpt = new ScriptingOptions();
//SQL command to execute DDL in destination database
SqlCommand sql = new SqlCommand();
sql.Connection = conn;
conn.Open();
//this can changed to views, SPs, etc. as needed
foreach (Table t in db.Tables)
{
//check for system objects
if (!t.IsSystemObject)
{
StringCollection sc = t.Script(scriptOpt);
foreach (string s in sc)
{
//assign and execute DDL
sql.CommandText = s;
sql.ExecuteNonQuery();
}
}
}
}

An expression of non-boolean type specified in a context where a condition is expected, near 'NAME'.'

My code:
string SqlSelectQuery = " Select * From [KTS MANAGMENT] Where STAFF NAME=" + Convert.ToString(textBox1.Text);
SqlCommand cmd = new SqlCommand(SqlSelectQuery, CON);
SqlDataReader dr = cmd.ExecuteReader();
I get this error:
An expression of non-boolean type specified in a context where a condition is expected, near 'NAME'
You should always use parametrized queries to avoid SQL injection - still the #1 vulnerability in computing.
Thus, your code should be something like this:
string connectionString = "......"; // typically read from config file
string query = "SELECT * FROM [KTS MANAGMENT] WHERE STAFF NAME = #Name";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, con)
{
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = textBox1.Text;
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
// read the values from the SQL data reader....
}
con.Close();
}
This approach also avoid the error you have with missing and/or mismatched single or double quotes around strings in a SQL statement ...

System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near ')'

I have been trying to debug a piece of code and I have been thus far very unsuccessful in doing this.
I keep on getting this error
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near ')'
and I can't seem to see where the error is.
The code is below, having looked at various answers on this site and looked at the examples. The situation is that I am writing a program that accesses a database and is able to add and save data to that database. It is located on a server - though this is on my laptop.
I have written, re-written and copied the connection string to ensure there are no mistakes in it and even dropped a copy of the string into word and compared it to the one that is in the coding itself but to no avail.
public partial class AddingClients : Form
{
public AddingClients()
{
InitializeComponent();
}
String CompanyName2;
String ClientName2;
String CompanyAddress12;
String CompanyAddress22;
String CompanyAddress32;
String CompanyTown2;
String CompanyPostCode2;
String TelephoneNumber2;
String CompanyEMail2;
String CompanyNotes2;
String ClientReference2;
public SqlConnection con;
public void connection()
{
String connectionstr = #"Data Source=ACER\PATTESTSERVER;Initial Catalog=PatTest;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;";
con = new SqlConnection(connectionstr);
con.Open();
}
private void Finish_Click(object sender, EventArgs e)
{
ClientReference2 = Id.Text;
CompanyName2 = CompanyName.Text;
ClientName2 = ClientName.Text;
CompanyAddress12 = CompanyAddress1.Text;
CompanyAddress22 = CompanyAddress2.Text;
CompanyAddress32 = CompanyAddress3.Text;
CompanyTown2 = CompanyTown.Text;
CompanyPostCode2 = CompanyPostCode.Text;
TelephoneNumber2 = TelephoneNumber.Text;
CompanyEMail2 = CompanyEMail.Text;
CompanyNotes2 = CompanyNotes.Text;
String connectionstr = #"Data Source=ACER\PATTESTSERVER;Initial Catalog=PatTest;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;";
con = new SqlConnection(connectionstr);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO ClientTable(Id, ClientName, CompanyName, CompanyAddress1, CompanyAddress2, CompanyAddress3, CompanyTown, CompanyPostCode, TelephoneNumber, CompanyEMail, CompanyNotes,) VALUES(#parameter1, #parameter2, #parameter3, #parameter4, #parameter5, #parameter6, #parameter7, #parameter8, #parameter9, #parameter10, #parameter11,)", con);
cmd.Parameters.AddWithValue("#parameter1", ClientReference2);
cmd.Parameters.AddWithValue("#parameter2", ClientName2);
cmd.Parameters.AddWithValue("#parameter3", CompanyName2);
cmd.Parameters.AddWithValue("#parameter4", CompanyAddress12);
cmd.Parameters.AddWithValue("#parameter5", CompanyAddress22);
cmd.Parameters.AddWithValue("#parameter6", CompanyAddress32);
cmd.Parameters.AddWithValue("#parameter7", CompanyTown2);
cmd.Parameters.AddWithValue("#parameter8", CompanyPostCode2);
cmd.Parameters.AddWithValue("#parameter9", TelephoneNumber2);
cmd.Parameters.AddWithValue("#parameter10", CompanyEMail2);
cmd.Parameters.AddWithValue("#parameter11", CompanyNotes2);
cmd.ExecuteNonQuery();
//this method moves to the next screen.
this.Hide();
Asset M1 = new Asset();
M1.Show();
}
private void SaveandNext_Click(object sender, EventArgs e){
ClientReference2 = Id.Text;
CompanyName2 = CompanyName.Text;
ClientName2 = ClientName.Text;
CompanyAddress12 = CompanyAddress1.Text;
CompanyAddress22 = CompanyAddress2.Text;
CompanyAddress32 = CompanyAddress3.Text;
CompanyTown2 = CompanyTown.Text;
CompanyPostCode2 = CompanyPostCode.Text;
TelephoneNumber2 = TelephoneNumber.Text;
CompanyEMail2 = CompanyEMail.Text;
CompanyNotes2 = CompanyNotes.Text;
String connectionstr = #"Data Source=ACER\PATTESTSERVER;Initial Catalog=PatTest;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;";
con = new SqlConnection(connectionstr);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO ClientTable(Id, ClientName, CompanyName, CompanyAddress1, CompanyAddress2, CompanyAddress3, CompanyTown, CompanyPostCode, TelephoneNumber, CompanyEMail, CompanyNotes,) VALUES(#parameter1, #parameter2, #parameter3, #parameter4, #parameter5, #parameter6, #parameter7, #parameter8, #parameter9, #parameter10, #parameter11,)", con);
cmd.Parameters.AddWithValue("#parameter1", ClientReference2);
cmd.Parameters.AddWithValue("#parameter2", ClientName2);
cmd.Parameters.AddWithValue("#parameter3", CompanyName2);
cmd.Parameters.AddWithValue("#parameter4", CompanyAddress12);
cmd.Parameters.AddWithValue("#parameter5", CompanyAddress22);
cmd.Parameters.AddWithValue("#parameter6", CompanyAddress32);
cmd.Parameters.AddWithValue("#parameter7", CompanyTown2);
cmd.Parameters.AddWithValue("#parameter8", CompanyPostCode2);
cmd.Parameters.AddWithValue("#parameter9", TelephoneNumber2);
cmd.Parameters.AddWithValue("#parameter10", CompanyEMail2);
cmd.Parameters.AddWithValue("#parameter11", CompanyNotes2);
cmd.ExecuteNonQuery();
this.Hide();
AddingClients M1 = new AddingClients();
M1.Show();//Saves the current data then goes to the next record to be tested.
You have an extra comma before the closing ) in your column list and VALUES sections:
SqlCommand cmd = new SqlCommand("INSERT INTO ClientTable(Id, ClientName, CompanyName, CompanyAddress1, CompanyAddress2, CompanyAddress3, CompanyTown, CompanyPostCode, TelephoneNumber, CompanyEMail,
CompanyNotes,)
****
VALUES(#parameter1, #parameter2, #parameter3, #parameter4, #parameter5, #parameter6, #parameter7, #parameter8, #parameter9, #parameter10,
#parameter11,)", con);
****
Remove that and you should be fine

Error in oledb database connectivity

Connection
Conn_String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\UTS.mdb"
conn = New OleDbConnection(Conn_String)
conn.Open()
Query
sqlCmd.Connection = conn
sqlCmd.CommandText = "INSERT into Customer_Master Values (#Cust_ID,#Cust_Name,#Cust_Address,#Cust_ContactNo)"
sqlCmd.Parameters.AddWithValue("#Cust_ID", SqlDbType.Int).Value = Cust_id
sqlCmd.Parameters.AddWithValue("#Cust_Name", SqlDbType.Text).Value = txtcname.Text
sqlCmd.Parameters.AddWithValue("#Cust_Address", SqlDbType.Text).Value = txtcadd.Text
sqlCmd.Parameters.AddWithValue("#Cust_ContactNo", SqlDbType.Int).Value =
txtccontact.Text.ToString
sqlCmd.ExecuteNonQuery()
conn.Close()
Problem
When I Click the button containing the above code it gives me following error..
An unhandled exception of type System.NullReferenceException occurred in UTS.exe
Additional information: Object reference not set to an instance of an object.
The error is n this line-->sqlCmd.Connection = conn
When I searched in ExcuteNonQuery to check myself, I found this example first:
msdn
it shows an example of intialising a command object:
SqlCommand command = new SqlCommand(queryString, connection);

Resources