I wanted to populate data table with the value taken from the database. I want to use Select condition with the values taken from textbox.. I have written the following code in C#, please tell me whether it is a right approach. It is showing exception about connection string.. but I wanted to know whether my approach is correct or not.. please do comment.
public partial class searchsale : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\rdb.mdf;Integrated Security=True;User Instance=True");
conn.Open();
string scriptname = TextBox1.Text;
string accnum = TextBox2.Text;
string sql = #"select scriptname,accnum,Quantity,price from transac where scriptname = #sn, accnum = #an and transactio = 'Sell'";
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#an", accnum);
cmd.Parameters.AddWithValue("#sn", scriptname);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = GetDataTable(sql);
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}
private DataTable GetDataTable (string sql)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(dt);
}
return dt;
}
}
The error with your code is because you have not set the connection property of your command .
and for using data table the most simple way is using :
try
{
var connection = #"your connection string";
//your command
var command = "your command";
var dataAdapter = new System.Data.SqlClient.SqlDataAdapter(command, connection);
var dataTable = new DataTable();
//Get data
dataAdapter.Fill(dataTable);
}
catch (System.Data.SqlClient.SqlException sqlEx)
{
//Use sqlEx.Number to hanlde excception more specific
//for example if sqlEx.Number -1 => Could Not Connect to Server.
}
catch (Exception ex)
{
}
Problem is in your below code line for GetDataTable (string sql) method. You will have to use ConnectionString property. I would suggest you to read about ADO.NET more from MSDN.
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
Should be
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString
It should look like
using (SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
your code looks right except the connection string. You have declared the connection string at the beginning as
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\rdb.mdf;Integrated Security=True;User Instance=True");
But in your connection initialization it looks like you are getting it from App config file.
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
So instead of having connection in your code put it in the app config file and remove the connection from your code
something like this
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="ConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\rdb.mdf;Integrated Security=True;User Instance=True"/>
</connectionStrings>
</configuration>
Thank you,
Birhanu
public static class SqlDBHelper
{
public static DataSet ExecuteDataSet(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
using (DataSet ds = new DataSet())
using (SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, connStr))
{
cmd.CommandType = cmdType;
foreach (var item in parameters)
{
cmd.Parameters.Add(item);
}
try
{
cmd.Connection.Open();
new SqlDataAdapter(cmd).Fill(ds);
}
catch (Exception ex)
{
throw ex;
}
return ds;
}
}
}
Related
I have the following code, but I can't seem to manipulate it to work the way I want. I would like to have the command search the data base for the first entry in the database that matches textbox2.text and delete the row.
private void button4_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\DillPickle\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From ACCNT where ACCNTNUM=" + textBox2.Text , con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
ACCNT."txtbox2.text".Rows[0].Delete();
}
else
{
MessageBox.Show("The account does not exist in the record!");
}
}
There's many ways to accomplish what you are trying to do; here's one way:
private readonly string SqlConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\DillPickle\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30";
private readonly string SqlDeleteQuery = "DELETE FROM ACCNT WHERE ACCNTNUM=#accountNumber";
private void button4_Click(object sender, EventArgs e)
{
try
{
using (var sqlConnection = new SqlConnection(SqlConnectionString))
using (var sqlCommand = sqlConnection.CreateCommand())
{
sqlConnection.Open();
sqlCommand.CommandText = SqlDeleteQuery;
sqlCommand.Parameters.AddWithValue("#accountNumber", textBox2.Text);
sqlCommand.ExecuteNonQuery();
}
}
catch (Exception ex)
{
// Do something with the exception, like log it...
}
}
I'm trying to fill a datagridview with SQL Server table data and I get an error:
ExecuteReader: Connection property has not been initialized.
How do I fix this ?
private void BlackListLoad()
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
BindingSource bs = new BindingSource();
var table = dt;
var connection =
#"Data Source=someone-someone\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
using (var con = new SqlConnection { ConnectionString = connection })
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
try
{
cmd.CommandText = #"SELECT * FROM [dbo].[Blacklist1]";
table.Load(cmd.ExecuteReader());
bs.DataSource = table;
ListGrid.ReadOnly = true;
ListGrid.DataSource = bs;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message + " sql query error.");
}
}
}
You haven't given your SqlCommand a connection! As it states you need to do this. You can fix this by doing:
cmd.Connection = con; just before you execute the reader.
Read here for more information: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.connection(v=vs.110).aspx
It also looks like you're not opening your connection, which can be fixed with:
con.Open();
With a new connection object, you do not need to check whether it's open, because it won't be.
Try it this way.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Authors";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Authors_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
}
}
}
This is what I have so far:
static void Main(string[] args)
{
DataTable t = new DataTable();
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=local.url;Initial Catalog=databasename;User ID=username;Password=password";
cnn = new SqlConnection(connetionString);
string sql = "SELECT * FROM shiplabels";
SqlDataAdapter a = new SqlDataAdapter(sql, cnn);
try
{
cnn.Open();
a.Fill(t);
cnn.Close();
}
catch (Exception ex)
{
Console.WriteLine ("Can not open connection ! ");
}
}
I want to connect to this Microsoft DB and pull data from it. I am having trouble just getting this to work! When I use this code datatable t has 0 rows where it should come back with a few hundred. I'm clearly missing something simple here?
DataTable dt = new DataTable();
SqlDataAdapter sqlAdtp = new SqlDataAdapter();
string connectionString = "Data Source=local.url;Initial Catalog=databasename;User ID=username;Password=password";
string sql = "SELECT * FROM shiplabels";
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.CommandType = CommandType.Text;
try
{
sqlAdtp.SelectCommand = cmd;
sqlAdtp.Fill(dt);
}
catch (Exception ex)
{
}
}
}
First, you don't need to open the connection when using SqlDataAdapter.
Also, you forgot the CommandType.
This should work fine for you.
using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection sqlCnn ;
SqlCommand sqlCmd ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Select * from product";
sqlCnn = new SqlConnection(connetionString);
try
{
sqlCnn.Open();
sqlCmd = new SqlCommand(sql, sqlCnn);
adapter.SelectCommand = sqlCmd;
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0] + " -- " + ds.Tables[0].Rows[i].ItemArray[1]);
}
adapter.Dispose();
sqlCmd.Dispose();
sqlCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
OracleConnection con = new OracleConnection();
con.ConnectionString = "User id =test;password=test1;Datasource=oracle";
myConnection.Open();
}
Above is the code that I am using. It will be called on page_Load.
Follow below steps,below is my sample example:
1.In Web.config of your file add below string
<connectionStrings>
<add name="CustomerDataConnectionString" connectionString="Data Source=.;User Id=*;Password=*;Integrated Security=SSPI;Initial Catalog=Northwind;OLEDB.NET=True" providerName="Oracle.DataAccess.Client"/>
</connectionStrings>
//* must be filled with your credentials
2.Now in the code behind file,Import namespace for oracle client and Configuration manager for oracle client and below code
using System.Data.OracleClient;
using System.Data;
using System.Configuration;
3.Write below code in your Page_Load event:Cmd can be SQL command
static string strConnectionString = ConfigurationManager.ConnectionStrings["CustomerDataConnectionString"].ConnectionString;
using (OracleConnection con = new OracleConnection(strConnectionString))
{
try
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
using (OracleDataAdapter da = new OracleDataAdapter(cmd))
{
table = new DataTable();
da.Fill(table);
}
}
catch (Exception ex)
{
throw ex;
}
}
}
Refer this link http://www.connectionstrings.com/ for more inforamtion
string oradb = "User id =test;password=test1;Datasource=oracle";
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
using (OracleDataAdapter a = new OracleDataAdapter(
"SELECT id FROM emp1", conn))
{
DataTable t = new DataTable();
a.Fill(t);
// Render data onto the screen
dataGridView1.DataSource = t;
}
conn.Dispose();
Make sure you have included the required libraries,
try using this code ,
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=12345;database=test;";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = myConnectionString;
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
It's always better to have try-catch. that helps you track the exact error if you are stuck somewhere.
I wrote this code but I do not know why this line gives error!
String sname = dr.GetString ("name");
My code:
SqlConnection cn = new SqlConnection(
"Data Source=.;Initial Catalog=logindb;Integrated Security=True");
string query1 = "select * from tbllogin";
SqlCommand cmd = new SqlCommand(query1);
SqlDataReader dr;
try
{
cn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
String sname = dr.GetString("name");
comboBox1.Items.Add(sname);
}
}
catch (Exception e)
{
// do smth about exception
}
First of all you have to check this again:
SqlConnection cn = new SqlConnection(
"Data Source=.;Initial Catalog=logindb;Integrated Security=True");
Data Source=.; This is wrong and it will give you an error.
After that you can use the code below to achieve what you want. The code below also uses using statement to dispose the connection.
using (
SqlConnection connection = new SqlConnection(strCon)) // strCon is the string containing connection string
{
SqlCommand command = new SqlCommand("select * from tbllogin", connection);
connection.Open();
DataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
comboBox1.Items.Add(reader.GetString(int index)); // index of column you want, because this method takes only int
}
}
reader.Close();
}
(Amazingly) GetString only take an index as parameter.
See MSDN
public override string GetString(int i)
With no other signatures :-(
However you could write:
String sname = dr.Item["name"].ToString();
MSDN says that SqlDataReader.GetString method accepts an int as a parameter, which is the index of the column.
What you need is this:
while (dr.Read())
{
String sname = (string)dr["name"];
comboBox1.Items.Add(sname);
}
Here's your code:
SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=logindb;Integrated Security=True");
string query1 = "select * from tbllogin"; SqlCommand cmd = new SqlCommand(query1); SqlDataReader dr;
try {
cn.Open(); dr = cmd.ExecuteReader();
while (dr.Read())
{ String sname = (string)dr["name"];
comboBox1.Items.Add(sname);
}
}
catch (Exception e) { MessageBox.Show(e.Message, "An error occurred!"); }
The catch block wasn't written correctly, you missed the (Exception e) part.