How do I connect to a SQL database from C#? - c#

I am trying to write a local program management and install system for my home network, and I think I've got the technologies nailed down:
C#/.NET/WPF for the client
Lua for installation scripting support (through LuaInterface)
SQL Server Express for maintaining a database of programs
However I'm unsure what specifically I'll use to connect C# to the database. Is there something built into the .NET framework for this? Bonus points if you have a suggestion on what I should use for interacting with said database.

Check out
Introduction to ADO.NET Tutorial
ADO.NET Tutorial Lesson 1
An introduction to ADO.NET
I'm sure there's plenty more out there - just google for "ADO.NET" and "Tutorial" ......
UPDATE:
If you want to connect to your local SQL Server Express, and connect to the "Northwind" database, and read the top 5 customers from the "Customers" table, you'd have to do something like this:
string connectionString = "server=(local)\SQLExpress;database=Northwind;integrated Security=SSPI;";
using(SqlConnection _con = new SqlConnection(connectionString))
{
string queryStatement = "SELECT TOP 5 * FROM dbo.Customers ORDER BY CustomerID";
using(SqlCommand _cmd = new SqlCommand(queryStatement, _con))
{
DataTable customerTable = new DataTable("Top5Customers");
SqlDataAdapter _dap = new SqlDataAdapter(_cmd);
_con.Open();
_dap.Fill(customerTable);
_con.Close();
}
}
Now you would have all 5 top customers from your Northwind database in the DataTable and you can inspect them, print them out, manipulate them - whatever you want to do.
That's ADO.NET in action!
As for the details of the connection string - what options you can use and what it should look like, check out the Connection Strings web site - it has tons of examples and explanations.
Marc

SqlConnection
object is made for this.
Eg:
SqlConnection conn = new SqlConnection(
"Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");
or
SqlConnection conn = new SqlConnection(
"Data Source=DatabaseServer; Initial Catalog=Northwind; User ID=YourUserID; Password=YourPassword");
conn.Open(); // opens the database connection
Edit:
After doing all your stuff you have to close the connection by
conn.Close();
Data Source: Identifies the server. Could be local machine, machine domain name, or IP Address.
Initial Catalog: Database name.
Integrated Security: Set to SSPI to make connection with user's Windows login
User ID: Name of user configured in SQL Server.
Password: Password matching SQL Server User ID.

To connect to SQL Server Express you need nothing but System.Data, which is a standard .NET assembly. Just use SqlXXX classes and you'll be done.
However, writing mundane ADO.NET code is very boring, so it's very common to use an ORM or less heavy-weight result-set mapper such as BLToolkit.
And finally, consider using SQL Server CE. This is a fully ACID-compliant single-file embedded database engine which supports pretty much any feature you can expect form an SQL RDBMS.

You can use ADO.Net and System.Data.SqlClient namespace for the same. I will advise you to go with Entities framework (ORM). Please find below links for Entity Framework walk through
http://thedatafarm.com/LearnEntityFramework/tutorials/creating-an-ado-net-entity-framework-entity-data-model/
http://thedatafarm.com/LearnEntityFramework/tutorials/use-an-entity-framework-entity-as-a-winforms-data-source/

I would recommend using Microsoft's Patterns & Practices Enterprise Library. You would specifically be using the The Data Access Application Block.
An excerpt from MSDN:
The Data Access Application Block
provides the following benefits:
It uses the functionality provided by ADO.NET 2.0 and with it, you can
use ADO.NET functionality along with
the application block's functionality.
It reduces the need to write boilerplate code to perform standard
tasks.
It helps maintain consistent data access practices, both within an
application and across the enterprise.
It reduces difficulties in changing the database type.
It relieves developers from learning different programming models
for different types of databases.
It reduces the amount of code that developers must write when they port
applications to different types of
databases.
I've used this method for years and it's been very successfull thus far. Good luck!

I wish this will help
just try these..
#CLASS
using System.Data;
using System.Data.SqlClient;
namespace WindowsFormsApplication2
{
class clsDB
{
public SqlDataAdapter mDataAdapter = new SqlDataAdapter();
public DataSet mDataSet = new DataSet();
public SqlConnection mConn;
public clsDB()
{
mConn = new SqlConnection("Data Source=(the data source);Initial Catalog=sample;User ID=(the id);Password=(the password)");
}
public void SQLDB(string strSQL)
{
try
{
mDataAdapter = new SqlDataAdapter(new SqlCommand(strSQL, mConn));
mDataSet = new DataSet();
mDataAdapter.Fill(mDataSet);
}
catch (Exception ex)
{
throw ex;
}
finally
{
mConn.Close();
}
}
public void ClearRes()
{
mDataAdapter.Dispose();
mDataAdapter = null;
mDataSet.Dispose();
if (mConn.State != ConnectionState.Closed)
{
mConn.Close();
}
}
}
}
#LOGIN
public partial class Login : Form
{
clsDB x = new clsDB();
public Login()
{
InitializeComponent();
}
private void btnSubmit_Click(object sender, EventArgs e)
{
x.SQLDB("select * from tbl_accounts where u_username ='" + txtUser.Text + "' and u_password ='" + txtPass.Text + "'");
if (x.mDataSet.Tables[0].Rows.Count > 0)
{
Main a = new Main();
this.Hide();
a.Show();
}
else
{
MessageBox.Show("wrong username or password");
}
}
#MAIN ACCESS
namespace WindowsFormsApplication2
{
public partial class Main : Form
{
clsDB x = new clsDB();
public Main()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
x.SQLDB("insert into tbl_info (u_lastname, u_firstname, u_middlename) values ('" + atxtLN.Text + "','" + atxtFN.Text + "','" + atxtFN.Text + "')");
fillgrid();
}
private void Main_Load(object sender, EventArgs e)
{
x.SQLDB(" select * from tbl_info ");
dgv1.DataSource = x.mDataSet.Tables[0];
fillgrid();
}
void fillgrid()
{
x.SQLDB("select * from tbl_info");
dgv1.DataSource = null;
dgv1.DataSource = x.mDataSet.Tables[0];
}
void search()
{
x.SQLDB("SELECT * from tbl_info where u_id like '" + etxtID.Text + "%' order by u_id");
if (x.mDataSet.Tables[0].Rows.Count > 0)
{
x.mDataAdapter.Fill(x.mDataSet, "tbl_info");
dgv1.DataSource = x.mDataSet.Tables["tbl_info"].DefaultView;
etxtLN.Text = dgv1.Rows[dgv1.CurrentRow.Index].Cells["u_lastname"].Value.ToString();
etxtFN.Text = dgv1.Rows[dgv1.CurrentRow.Index].Cells["u_firstname"].Value.ToString();
etxtMN.Text = dgv1.Rows[dgv1.CurrentRow.Index].Cells["u_middlename"].Value.ToString();
}
else if (etxtID.Text == "Type User ID to Edit")
{
etxtLN.Text = "";
etxtFN.Text = "";
etxtMN.Text = "";
}
else
{
etxtLN.Text = "";
etxtFN.Text = "";
etxtMN.Text = "";
}
}
private void etxtID_TextChanged(object sender, EventArgs e)
{
}
private void etxtID_Enter(object sender, EventArgs e)
{
etxtID.Text = "";
etxtID.ForeColor = Color.Black;
}
private void etxtID_Leave(object sender, EventArgs e)
{
if (etxtID.Text == "")
{
etxtID.ForeColor = Color.Gray;
etxtID.Text = "Type User ID to Edit";
x.SQLDB(" select * from tbl_info ");
dgv1.DataSource = x.mDataSet.Tables[0];
fillgrid();
}
}
private void etxtID_KeyUp(object sender, KeyEventArgs e)
{
search();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
x.SQLDB("UPDATE tbl_info set u_lastname ='" + etxtLN.Text + "', u_firstname ='" + etxtFN.Text + "', u_middlename ='" + etxtMN.Text + "' where u_id =" + etxtID.Text);
MessageBox.Show("Operation Successful!");
fillgrid();
}
private void btnDelete_Click(object sender, EventArgs e)
{
x.SQLDB("delete from tbl_info where u_id =" + dtxtID.Text + "");
MessageBox.Show("Operation Successful!");
fillgrid();
}
}
}

Currently the easiest way to connect to your database and perform queries in C# is LinqToSQL. It will save you a lot of headache as compared to using "old-school" ADO connections.

Sure of course, you can just use the classes in System.Data.SqlClient, though most people will use an ORM. I use LLBLGen Pro.

You can use https://github.com/MohamadParsa/AdoDbConnection.Net and use the project as a project reference in your solution and enjoy. Also, you can explore DBConnection.cs file and copy class or method in your project.
but ... for make a connection or disconnect to express you can use:
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
string _ErorrString = "";
string _InternalErorrString = "";
private void Connect()
{
cmd.Connection = con;
da.SelectCommand = cmd;
try
{
string cs = "";
cs = #"Data source=.\SQLEXPRESS;Attachdbfilename=|DataDirectory|\"
+ DataBbaseName + ".mdf;Integrated security=true;user Instance=true";
con.ConnectionString = cs;
con.Open();
}
catch (Exception ex)
{
_ErorrString += "Erorr NO. : 100" + ", connection error.";
_InternalErorrString += ex.Message;
}
}
private void Disconnect()
{
con.Close();
}
and to execution command and get results:
public DataSet RunAndGet(string sql)
{
//first, make a connection
Connect();
//to hold and return results
DataSet dataSet = new DataSet();
try
{
//set command
cmd.CommandText = sql;
//run and fill results into the dataset
da.Fill(dataSet);
}
catch (Exception ex)
{
_ErorrString += "Erorr NO. : 101" + ", internal error.";
_InternalErorrString += ex.Message;
}
//finally closes connection
Disconnect();
return dataSet;
}

Related

The data i inserted does not show in the DataBase

I have an form that looks like that.Whenever I insert the Name and Age into the database and i press Show,it shows me all the entries(including the ones I just entered) but in the dbo.Table it does not update,everytime I try to refresh it gives me an error like this
I created the data base using Add->New Item->Service Base DataBase
This is the code for Inserting data:
private void button1_Click(object sender, EventArgs e)
{
string sql = "Insert into Elevi(Name,Age) values(#Name,#Age)";
command = new SqlCommand(sql, myConnection);
try
{
command.Parameters.AddWithValue("#Name", textBox1.Text);
command.Parameters.AddWithValue("#Age", Convert.ToInt32(textBox2.Text));
command.ExecuteNonQuery();
}
catch(Exception a)
{
MessageBox.Show(a.Message);
}
}
This is the code for Showing the data:
private void button2_Click(object sender, EventArgs e)
{
string sql;
try
{
sql = "Select * from Elevi";
command = new SqlCommand(sql, myConnection);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
int IdCitit = Int32.Parse(dataReader.GetValue(0).ToString());
string NumeCitit = dataReader.GetValue(1).ToString();
int VarstaCitita = Int32.Parse(dataReader.GetValue(2).ToString());
MessageBox.Show($"Nume : {NumeCitit} \n Varsa : {VarstaCitita} \n Id: {IdCitit}");
}
}
catch (Exception Exceptie)
{
MessageBox.Show(Exceptie.Message);
}
}
For example, if I have the following input and i Press the button for printing the data it will work just fine
,but after I close the form and check the dbo.Elevi[Data] the new input will not be inserted there
The connection string is : #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\TestareDataBase.mdf;Integrated Security=True"
I got it from Project->Add new DataSource
I think you code is not wrong, it seams like it is a database error. Perhaps the database file was created with a newer version of SQL Server Express than the one installed on your machine? Your SQL tools in VS are not compatible with the SQL server. Check the versions of the SQL tools.
Usually it happens when transaction doesn't get committed and it remains in memory, thus if we check the values by using same connection then we find latest one but when we try to verify it from table by using other connection we don't find it unless program commits the transaction.
try this:
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(myConnection))
{
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction = connection.BeginTransaction("MyTransaction");
command.Connection = connection;
command.Transaction = transaction;
try
{
command.CommandText = $"Insert into Elevi(Name,Age) values({textBox1.Text},{textBox2.Text})";
command.ExecuteNonQuery();
transaction.Commit();
}
catch(Exception a)
{
MessageBox.Show(a.Message);
}
}
}

Retrieve single user data from oracle database into visual studio C# application

I am using forms in visual studio to create an application and then retrieve data from Oracle database. My all parts are working except getting data for the single user. Here is form.cs section for that part
private void getCustomerStringToolStripMenuItem_Click(object sender, EventArgs
e)
{
Getcuststring g = new Getcuststring();
g.Show();
}
This is my partial class named getcuststring.cs
namespace Assignment
{
public partial class Getcuststring : Form
{
public Getcuststring()
{
InitializeComponent();
}
private void Getcuststring_Load(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Getting();
}
public void Getting()
{
OracleConnection conn = new OracleConnection();
conn.ConnectionString = "Data Source=(DESCRIPTION =" + "(ADDRESS = (PROTOCOL = TCP)" +
"(HOST = *******)(PORT = 1521))" + "(CONNECT_DATA =" + "(SID = dms)));"
+ "User Id= *****;Password= ******;";
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "GET_CUST_STRING_FROM_DB";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("pcustid", OracleDbType.Long).Value = textBox1.Text;
cmd.Parameters.Add("return_value", OracleDbType.Varchar2).Direction = ParameterDirection.ReturnValue;
try
{
cmd.ExecuteNonQuery();
// string result = string.Empty;
var result = cmd.Parameters["result_value"].Value.ToString();
MessageBox.Show(result);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
my all other functions are working but when executing this in visual studio it every time give exception out saying no data is found whereas that customer id is present in the Oracle database but it somehow not showing the result but instead raising the exception.
So can u tell me where I am wrong, why he's providing me with an exception saying no data found whereas that data actually exist.
This is the function
CREATE OR REPLACE FUNCTION GET_CUST_STRING_FROM_DB(pcustid NUMBER) RETURN
VARCHAR2 AS
vcustid NUMBER;
vcustname VARCHAR2(255);
vcustsales NUMBER;
vcuststatus VARCHAR2(255);
BEGIN
SELECT CUSTID,CUSTNAME,SALES_YTD,STATUS INTO
vcustid,vcustname,vcustsales,vcuststatus
FROM CUSTOMER
WHERE CUSTID = pcustid;
RETURN 'CustID: ' || vcustid || ' Name: ' || vcustname || ' Status: ' ||
vcuststatus || ' SalesYTD: ' || vcustsales;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR(-20021,'Customer ID not found');
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-20000,SQLERRM);
END;
I think it is simple typo, line
var result = cmd.Parameters["result_value"].Value.ToString();
should be:
var result = cmd.Parameters["return_value"].Value.ToString();
I built similiar case, and got System.IndexOutOfRangeException when I run it. Correcting typo solved problem. Whole code which worked for me:
OracleConnection CONNECTION
= new OracleConnection("Data Source=XX;User Id=XX;Password=XX;");
CONNECTION.Open();
OracleCommand cmd = new OracleCommand() { Connection = CONNECTION };
cmd.CommandText = "GET_CUST_STRING_FROM_DB";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("pcustid", OracleType.Double).Value = textBox1.Text;
cmd.Parameters.Add("return_value", OracleType.VarChar, 500).Direction
= System.Data.ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
var result = cmd.Parameters["return_value"].Value.ToString();
Console.WriteLine(result);
CONNECTION.Close();

I get this error when running my program i debug: System.Data.SqlClient.SqlException: 'Invalid object name 'Login'.'

I'm trying to construct a log in using the SqlServer which I'm not so familiar with. I don't ask for a very precise answer but more of a point in a general direction where the error may be. Should I learn more about the SqlServer to solve this problem or is the error somewhere else?
namespace Log_in
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnLogIn_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Joel\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter sda = new SqlDataAdapter("SELECT COUNT(*) FROM Login WHERE Username='" + tbxLogIn.Text + "'AND Password ='"+tbxPassword.Text+"'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
Main ss = new Main();
ss.Show();
}
else
{
MessageBox.Show("Incorrect log in details.");
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
That error means it's not seeing Login. Either the table isn't there or you need to access it via schema.
This code is vulnerable to SQL Injection attacks. Please learn about parameterized queries or use something like Entity Framework. More Info on how parameterized queries solves the problem.

ADO.NET programming says error occured - ExecuteNonQuery requires an open and available connection

Right now, my professor requires me to implement a case study using ADO.NET to save data into SQL Server. I have already created a database and tables in SQL Server and I'm trying to create some forms in Visual Studio by C# ADO.NET. I write according to a YouTube video. But I don't know why I cannot save my data to database successfully.
The result as I write my code like this.
Any help would be appreciated.
namespace casestudy
{
public partial class Form2 : Form
{
SqlConnection vcon2 = new SqlConnection(#"Data Source=SOPHIA-PC\SQLEXPRESS;Initial Catalog=casestudy;Integrated Security=True");
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
try
{
vcon2.Open();
}
catch (Exception ex)
{
MessageBox.Show("error.occured" + ex.Message);
this.Dispose();
}
}
private void button1_Click(object sender, EventArgs e)
{
string vsql = string.Format("insert into Calluser values ({0}, '{1}', '{2}', {3})", Int32.Parse(txtUserID.Text), txtFName.Text, txtLName.Text, Int32.Parse(txtZoneID.Text));
SqlCommand vCom = new SqlCommand(vsql, vcon2);
try
{
vCom.ExecuteNonQuery();
vCom.Dispose();
MessageBox.Show("The User Information stored.");
txtZoneID.Text = "";
txtLName.Text = "";
txtFName.Text = "";
txtUserID.Text = "";
txtUserID.Focus();
}
catch (Exception ex)
{
MessageBox.Show("error.occured" + ex.Message);
this.Dispose();
}
}
}
}
Can you add a check to see if the connection is actually open and if not reopen it just before you call the ExecuteNonQuery()
if (vcon2.State != ConnectionState.Open)
{
vcon2.Open();
}
vCom.ExecuteNonQuery();
Opening the connection when the application or form opens is probably not the best approach. You want to open the connection right before you execute your sql and close it as soon as possible.
That being said, I recommend removing the code from the Form2_Load event. And do everything in the button1_Click or another method you call from there. Even better would be to have a class or component that does the data access for your application. Also use a using statement as it will ensure resources are disposed even if an exception is thrown.
using (SqlConnection connection = new SqlConnection(#"Data Source=SOPHIA-PC\SQLEXPRESS;Initial Catalog=casestudy;Integrated Security=True");))
{
SqlCommand command = new SqlCommand(vsql, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
Some info on the using statement:
http://www.dotnetperls.com/using
https://msdn.microsoft.com/en-us/library/yh598w02.aspx

Unable to insert row into table using an Oracle Connection

I would like to know what's the problem, or your advice to connect to Oracle. I'm trying with this but when I try to insert values, it doesn't work.
I'm using the Visual Web Developer 2008 and when I add a database on Database Explorer connections, it's working. But when I try to connect via this connection string, it doesn't work. What am I missing?
I don't get an exception, so apparently it's working well. But this code apparently doesn't insert! The id column is a varchar(45). I created the table "test" just for testing purposes.
using System.Data;
using System.Data.OracleClient;
public partial class _Default : System.Web.UI.Page
{
//string oradb = "Data Source=localhost;User ID=root;Password=jesua;Unicode=True;";
String oracle = "User ID=root;Password=jesua;Unicode=True;Data Source=localhost;";
OracleConnection con = new OracleConnection();
public void Conectar() {
try
{
con.Close();
con.ConnectionString = oracle;
con.Open();
}
catch(Exception ex){
throw new Exception("No Conecto " + ex);
}
}
public void desconectar() {
// con.ConnectionString = oracle;
con.Close();
}
public void agregar() {
this.Conectar();
OracleCommand query = new OracleCommand("INSERT INTO testing (id) VALUES ('testing')");
query.ExecuteNonQuery();
desconectar();
}
protected void Button1_Click(object sender, EventArgs e)
{
try {
agregar();
}
catch(Exception ex){
Console.Write("No agrego " + ex);
}
TextBox1.Text = "Conected";
}
}
--------------------------UPDATE------------------
So,
i found the way to do that,
i hope anyone here can use this code in a future...
This code creates the connection betwen Oracle and asp.net C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Oracle.DataAccess.Client; // ODP.NET Oracle managed provider
using Oracle.DataAccess.Types;
namespace proyecto
{
public partial class WebForm1 : System.Web.UI.Page
{
public void dbconnect() {
string oradb = "Data Source=localhost;User ID={Yoir ID};Password={Your Password};";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO TESTING(id) VALUES ('valor')";
int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated == 0)
Console.Write("Record not inserted");
else
Console.Write("Success!");
conn.Dispose();
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
this.dbconnect();
}
}
}
Good Luck!
The connection string that works for me is
connectionString="Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1522))
(CONNECT_DATA=(SERVICE_NAME=XE)));User Id=system;Password=pass;"
providerName="Oracle.DataAccess.Client"/>
It seems that you are missing the Service Name and Provider Name. You can find the service name in tnsnames.ora file which will be in your installation directory. Also make sure you have installed ODP.NET for Oracle 11g correctly, added reference to the Oracle.DataAccess.dll into your project and add the Provider Name in the connection string.

Categories