Connect with OleDbConnection - c#

I am trying to connect to a database with two tables. However, after I try and log in, I have an error. The error says there is no row at spot zero. I think this is because of my connection:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
namespace Project3
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void login_Click(object sender, EventArgs e)
{
OleDbConnection connect = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\parodeghero\\Documents\\Visual Studio 2010\\Projects\\Project3\\Project3\\App_Data\\QA.mdb;Persist Security Info=True");
//set up connection string
OleDbCommand command = new OleDbCommand("select * from Employee where Login=#login", connect);
OleDbParameter param0 = new OleDbParameter("#login", OleDbType.VarChar);
param0.Value = employeeID.Text;
command.Parameters.Add(param0);
//middle tier to run connect
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataSet dset = new DataSet();
da.Fill(dset);
//problem line
if (dset.Tables[0].Rows[0]["Password"].ToString().Equals(password.Text))
{

You need to open the connection
protected void login_Click(object sender, EventArgs e)
{
string pathToYourFileMDB = #"C:\yourPathHere\File.mdb";
try
{
OleDbConnection connect = new OleDbConnection($"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={pathToYourFileMDB};Persist Security Info=True");
//set up connection string
OleDbCommand command = new OleDbCommand("select * from Employee where Login=#login", connect);
OleDbParameter param0 = new OleDbParameter("#login", OleDbType.VarChar);
param0.Value = employeeID.Text;
command.Parameters.Add(param0);
//open connection
connect.Open();
//middle tier to run connect
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataSet dset = new DataSet();
da.Fill(dset);
}
catch(Exception err)
{
Debug.WriteLine(err.Message);
}
}

You do NOT need to open the connection. OleDbDataAdapter.Fill will open the connection AND close it if it found it closed to start with. Fill leaves the connection in the state that it finds it.
I do question your SQL. My understanding of OleDb is that it does NOT support naming parameters in SQL. It needs a place holder "?" instead of #login. You need a Parameter for each placeholder and the parameters must be added in the order they occurr. If your SQL is not valid, then you will have either a SQL Exception or no data in the DataTable, i.e. NO row 0 !

oledb connection complete code
http://csharp.net-informations.com/data-providers/csharp-oledb-connection.htm
string connetionString = null;
OleDbConnection cnn ;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=yourdatabasename.mdb;";
cnn = new OleDbConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
curos

Related

how to build a SQL connection using C# in Visual Studio 2017?

I've always used Oledb Connection.
but now I need to connect with my Database via Sql connection
yet I don't know how to do so,
can some one provide me an example of a database connected with sql connection?
this code needs a sql connection to be done successfully.
protected void Button1_Click(object sender, EventArgs e)
{
string st = this.TextBox1.Text;
string sqlstr2 = "select * from hsinfo WHERE rname='"+st+ "'";
SqlCommand cmd = new SqlCommand(sqlstr2,);
using (SqlDataReader rd = cmd.ExecuteReader())
{
this.Label1.Text = rd["rmail"].ToString();
}
}
You can check the official Microsoft page for more details SqlConnection Class, but I will reproduce the given example below ...
Aditionally you can check also the Connection String Syntax linked in the previous link.
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
This is a simple example code and it's working. This might help you.
Here NextMonth,NextYear,ProcessedDate are auto calculated values comes from another function don't think about that.
String cs = #"Data Source=LENOVO-G510;Initial Catalog=Nelna2;Persist Security Info=True;User ID=sa;Password=123";
protected void Save_Click(object sender, EventArgs e)
{
// SqlConnection con = new SqlConnection(cs);
using (SqlConnection con = new SqlConnection(cs))
{
try
{
SqlCommand command5 = new SqlCommand("insert into MonthEnd (month,year,ProcessedDate) values (#month2,#year2,#ProcessedDate2) ", con);
command5.Parameters.AddWithValue("#month2", NextMonth);
command5.Parameters.AddWithValue("#year2", NextYear);
command5.Parameters.AddWithValue("#ProcessedDate2", ProcessedDate);
command5.ExecuteNonQuery();
}
catch (SqlException ex)
{
Response.Write(ex.Message);
}
}
}
Connection string can be found in DB properties. right click on DB -> properties and Get the Connection String
There is no enougth information to build connection for you, but in the shortes you sth like this:
Server=...;Database=...;User ID=...;Password=...;
For more information just check ConnectionStrings website.
try below code and for more information about c# SQL server connection see this SQL Server Connection
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
I would do something like this:
public static List<Test> GetTests(string testVariable)
{
DataTable result = new DataTable();
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ConnectionString))
{
connection.Open();
GetQuery(
connection,
QueryGetTests,
ref result,
new List<SqlParameter>()
{
new SqlParameter("#testVariable", testVariable)
}
);
return result.Rows.OfType<DataRow>().Select(DataRowToTest).ToList();
}
}
private static void GetQuery(SqlConnection connection, string query, ref DataTable dataTable, List<SqlParameter> parameters = null)
{
dataTable = new DataTable();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.CommandTimeout = 120;
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
{
command.Parameters.Add(parameter);
}
}
using (SqlDataAdapter reader = new SqlDataAdapter(command))
{
reader.Fill(dataTable);
}
}
}
I think this can help you.
string sqlString = "select * from hsinfo WHERE rname=#st";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseName"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
cmd.Parameters.Add("#st", st);
using (SqlDataReader rd = cmd.ExecuteReader())
{
if (rd.Read())
{
this.Label1.Text = rd["rmail"].ToString();
}
}
}
}
Trick:
Create a file with .udl Extension on your Desktop
Run it by Double click
Compile form by Choosing provider, username, password, etc...
Test connection and save
Close the form
Open now the .udl file with Notepad
You will see the connection string that you can use with ADO.NET

Basic ASP Search SQL Server with a datagrid

im trying to follow a basic asp.net videos: https://www.youtube.com/watch?v=9e0kwADEoEg to create a web page that has a textbox, button and gridview.
For some reason the gridview will never show with populated data :/ I think its because of the .fill but really not sure. I can see the query when running a trace on sql server. just no output on the webpage!? Can anyone assist?
ausing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection vid = new SqlConnection("Server=localhost;Database=exam;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string str = "select F1,F2,F3,F4 from [dbo].[CandDbase] Where F4 = '#search'";
SqlCommand xp = new SqlCommand(str,vid);
xp.Parameters.Add("#search", SqlDbType.NVarChar).Value = TextBox1.Text;
vid.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds, "Name");
GridView1.DataSource = ds;
GridView1.DataBind();
vid.Close();
}
}
Get rid of the single quotes in the query:
string str = "select F1,F2,F3,F4 from [dbo].[CandDbase] Where F4 = #search";
The quotes tell Sql Server to treat #search as a string literal instead of an sql variable name.
Additionally, get rid of the ExecuteNonQuery() code. That function is for INSERT/UPDATE/DELETE statements.
Another issue is the SqlConnection object. Don't try to re-use the SqlConnection object in your page. .Net uses a feature called connection pooling to cache the underlying connection object, and trying to re-use the same .Net SqlConnection object instance conflicts with that. Just keep the connection string handy and create a new SqlConnection instance. Really.
There's more, too. The code below makes a number of other improvements: using so things are cleaned up in case of an exception, Fill() will open and close the connection for you, binding to a specific table, etc...
private const string cnString = "Server=localhost;Database=exam;Integrated Security=True";
protected void Button1_Click(object sender, EventArgs e)
{
string sql = "select F1,F2,F3,F4 from [dbo].[CandDbase] Where F4 = #search";
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(cnString))
using (SqlCommand xp = new SqlCommand(sql, con))
using (SqlDataAdapter da = new SqlDataAdapter(xp))
{
xp.Parameters.Add("#search", SqlDbType.NVarChar).Value = TextBox1.Text;
da.Fill(ds, "Name");
}
GridView1.DataSource = ds.Tables["Name"];
GridView1.DataBind();
}
// Open connection
using (SqlConnection c = new SqlConnection(vid))
{
c.Open();
// 2
// Create new DataAdapter
using (SqlDataAdapter a = new SqlDataAdapter(
"SELECT * FROM EmployeeIDs", c))
{
// 3
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
// 4
// Render data onto the screen
dataGridView1.DataSource = t; // <-- From your designer
}
}

Transfer data of a table from one database, to the same table of another database, using C# dataAdapter.Fill() and dataAdapter.Update()

I need to transfer the table's content to the same table located in another database, and I write this simple code using the C# dataAdapter.Fill() and dataAdapter.Update(), but it's seems not working like I supposed.
SqlConnection sqlConnection = new SqlConnection(strSqlConnectionString);
SqlConnection sqlConnection2 = new SqlConnection(strSqlConnectionString2);
sqlConnection.Open();
sqlConnection2.Open();
DataSet CustomerDataSet = new DataSet();
SqlDataAdapter sqlDA;
SqlDataAdapter sql2DA;
SqlCommandBuilder sqlCmdBuilder;
SqlCommandBuilder sqlCmdBuilder2;
sqlDA = new SqlDataAdapter("SELECT * FROM Articolo;", sqlConnection);
sqlDA2 = new SqlDataAdapter("SELECT * FROM Articolo;", sqlConnection2);
sqlCmdBuilder = new SqlCommandBuilder(sqlDA);
sqlCmdBuilder2 = new SqlCommandBuilder(sqlDA2);
sqlDA.Fill(CustomerDataSet, "Articolo");
sqlDA2.Fill(CustomerDataSet, "Articolo");
sqlDA2.Update(CustomerDataSet, "Articolo");`
What I want to do is to have the second db(string connection: strSqlConnectionString2) with updated data, taken from the first db, exploiting the functionality of dataAdapter.Fill() + dataAdapter.Update().
Is this possible? And can I do the same things but with Access db as a second db?
Can you try it this way?
using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
string connetionString;
OleDbConnection connection;
OleDbDataAdapter oledbAdapter;
OleDbCommandBuilder oledbCmdBuilder;
DataSet ds = new DataSet();
DataSet changes;
int i;
string Sql;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";
connection = new OleDbConnection(connetionString);
Sql = "select * from tblUsers";
try
{
connection.Open();
oledbAdapter = new OleDbDataAdapter(Sql, connection);
oledbAdapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
oledbCmdBuilder = new OleDbCommandBuilder(oledbAdapter);
changes = ds.GetChanges();
if (changes != null)
{
oledbAdapter.Update(ds.Tables[0]);
}
ds.AcceptChanges();
MessageBox.Show("Save changes");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

Cant get Datatable to fill because of "da.Fill(dt);" not working. please help, for an assignment

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 System.Data.OleDb;
namespace SDD_Single_Project___Michael
{
public partial class AllData : Form
{
private OleDbConnection connection = new OleDbConnection();
public AllData()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\schoolwork\Year 11\SDD\3 SINGLE TASK\SDD Single Project - Michael \SDD Single Project - Michael \bin\Persondata.accdb;
Persist Security Info=False;";
}
private void btnBack_Click(object sender, EventArgs e)
{
this.Hide(); //hides this page
MainScreen frm = new MainScreen(); //finds the next screen (the main game)
frm.Show(); //shows it
}
private void btnShow_Click(object sender, EventArgs e)
{
try
{
connection.Open(); //opens connection
OleDbCommand command = new OleDbCommand(); //declare our object of oleDB command
command.Connection = connection; // the connection is giving to the command
string query = "select * Persondata";
command.CommandText = query; // pass the query to the command
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt); // the error supposedly occurs here!!
dataGridView1.DataSource = dt;
connection.Close(); // closes the connection
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
}
}
the error code i get when i try running the program is that it is a syntax error at'*Persondata' on line 46 (which is theda.Fill(dt); line) and i cant figure it out. Please help its for an assignment.
This:
"select * Persondata"
must be
"select * FROM Persondata"

how to insert data into sql server in asp.net website?

I tried to insert data into sql server from my website build in vs 2008.For that I used button click event .I tried code shown in youtube but the code doesn't work .It shows error in my website.
The code in .aspx.cs file is
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
conn.Open();
}
protected void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into Insert values('"+txtCity.Text+"','"+txtFName.Text+"','"+txtLName.Text+"')",conn);
cmd.ExecuteNonQuery();
conn.Close();
Label1.Visible =true;
Label1.Text = "Your data inserted successfully";
txtCity.Text = "";
txtFName.Text = "";
txtLName.Text = "";
}
}
`
Okay, let's fix this code up just a little. You're getting there:
var cnnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var cmd = "insert into Insert values(#City,#FName,#LName)";
using (SqlConnection cnn = new SqlConnection(cnnString))
{
using (SqlCommand cmd = new SqlCommand(cmd, cnn))
{
cmd.Parameters.AddWithValue("#City",txtCity.Text);
cmd.Parameters.AddWithValue("#FName",txtFName.Text);
cmd.Parameters.AddWithValue("#LName",txtLName.Text);
cnn.Open();
cmd.ExecuteNonQuery();
}
}
A couple things to note about the modified code.
It's leveraging the using statement to ensure that resources are properly disposed.
It's parameterized to ensure that SQL Injection isn't a possibility.
It's not storing a connection object anywhere, get rid of that stored connection.
**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=mrinmoynandy;User ID=**;Password=****");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SumbitBtn_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into streg(Name,Father,Mother,Dob,Sex,Category,Maritial,Vill,Po,Ps,Dist,State,Pin,Country) values (#name,#father,#mother,#dob,#sex,#category,#maritial,#vill,#po,#ps,#dist,#state,#pin,#country)", con);
cmd.Parameters.AddWithValue(#"name", StNumTxt.Text);
cmd.Parameters.AddWithValue(#"father", FatNumTxt.Text);
cmd.Parameters.AddWithValue(#"mother", MotNumTxt.Text);
cmd.Parameters.AddWithValue(#"dob", DobRdp.SelectedDate);
cmd.Parameters.AddWithValue(#"sex", SexDdl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"category", CategoryDdl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"maritial", MaritialRbl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"vill", VillTxt.Text);
cmd.Parameters.AddWithValue(#"po", PoTxt.Text);
cmd.Parameters.AddWithValue(#"ps", PsTxt.Text);
cmd.Parameters.AddWithValue(#"dist", DistDdl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"state", StateTxt.Text);
cmd.Parameters.AddWithValue(#"pin", PinTxt.Text);
cmd.Parameters.AddWithValue(#"country", CountryTxt.Text);
con.Open();
con.Close();
}
}
Thanks
Mrinmoy Nandy
Phone No.: +91 9800451398
**
Creating procedure will avoid sql injection.
SQL
Create procedure insert
(#City,#FirstName,#LastName)
{
insert into tablename (City,FName,LName)
values(#City,#FirstName,#LastName)
}
C#
SqlConnection con=new sqlconnection("give ur connection string here");
sqlcommand cmd=new sqlcommand();
con.open();
cmd=new sqlcommand("insert",con);
cmd.commandtype=commandtype.storedprocedure;
cmd.parameters.addwithvalue("#City",txtCity.text);
cmd.parameters.addwithvalue("#FName",txtFName.text);
cmd.parameters.addwithvalue("#LNAme",txtLName.text);
cmd.ExecuteNonQuery();
con.close();

Categories

Resources