Why doesn't my dataset fill? - c#

I am adding a select statement from a mySQL database to a dataset but it does not fill the dataset.
Can anyone tell me what is wrong with my code?
string connString = "server = bla; user id = bla; Password = bla; database = bla;";
string query = "Select * From oc_product;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand mysqlcmd = new MySqlCommand(query, conn);
conn.Open();
MySqlDataAdapter da = new MySqlDataAdapter(mysqlcmd);
da.Fill(dsProducts);
conn.Close();

Related

Code deleting from datagrid but not in database

My code works in deleting information from the datagrid but does not delete it from the actual database. I am not sure how to fix this. Can i have some assistance please.
MySqlConnection sqlConnection = new MySqlConnection();
MySqlCommand sqlCommand = new MySqlCommand();
DataTable sqlData = new DataTable();
MySqlDataAdapter SqlAdapter = new MySqlDataAdapter();
DataSet sqlSet = new DataSet();
MySqlDataReader sqlDataReader;
//int dmlInfo;
String queried;
String server = "localhost";
String username = "root";
String password = "";
String database = "premiercare";
sqlConnection.Open();
sqlCommand.Connection = sqlConnection;
//removes from database (work to be done)
sqlCommand.CommandText = "Delete from premiercare.addpatient where id = #id";
sqlCommand = new MySqlCommand(queried, sqlConnection);
sqlConnection.Close();
//removes from dataGrid
foreach (DataGridViewRow items in this.dgAddPat.SelectedRows)
{
dgAddPat.Rows.RemoveAt(items.Index);
}
foreach (Control con in gbAddPat.Controls)
{
if (con is TextBox)
((TextBox)con).Clear();
}
loadInfo();
}
You need to make sure the connection and the queryString are correct and then you could do it like this:
//todo: make sure the connectionString is right
using (SqlConnection connection = new SqlConnection(connectionString))
{
//todo: build the right queryString
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
//no need to close the connection because of "using"

Load data Oracle Table to C# combobox using Oledb

hello i have create a table buy_unit in oracle database
CREATE TABLE buy_unit(
unit_id NUMBER(10) not null PRIMARY KEY,
unit_name VARCHAR2(10) not null
);
and insert Values
INSERT INTO BUY_UNIT
values(001,'Liter');
desc SELL_BUY_UNIT;
then create a combo box combobox1 in C# now can load buy_unit table data in combobox ? i have use the connection:
OleDbConnection con = new OleDbConnection("Provider=MSDAORA;Data Source=XE;User ID=user1;password=pssword");
Well, you can see below code which is refering SQLConnection. You can change as per your DB may be OracleConnection or so. While using SQL, we have pass connection string with UID and PWD.
For Oracle
have connection string as
string con = "Data Source=(DESCRIPTION =(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST = 000.00.0.00)(PORT = 0000)))(CONNECT_DATA =(SERVICE_NAME = database)));User ID=User/Schema;Password=password;Unicode=True";
public void BindComboBox()
{
SqlConnection con = new SqlConnection(#"server=ServerName; database = DBName ; User Id=sa; Password=PeaTeaCee5#");
con.Open();
string strCmd = "select desire column from table";
SqlCommand cmd = new SqlCommand(strCmd, con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.ExecuteNonQuery();
con.Close();
cbSupportID.DisplayMember = "name to display";
cbSupportID.ValueMember = "id";
cbSupportID.DataSource = ds;
cbSupportID.Enabled = true;
}
and try to use using block when you open DB connection as below
using (OracleConnection objConn = new OracleConnection(con))
{
\\ you code
\\ do your stuff
}
Code for Oracle. Excuse for syntax.
public void Fillcombo()
{
string oradb = " Data Source=xe;User Id=dbname;Password=pws; ";
string query = "select id , name from table";
OracleConnection condatabase = new OracleConnection(oradb);
OracleCommand cmddatabase = new OracleCommand(query, condatabase);
try
{
condatabase.Open();
OracleDataReader myReader = cmddatabase.ExecuteReader(); ;
myReader = cmddatabase.ExecuteReader();
while (myReader.Read())
{
string sname = myReader.GetInt32(0).ToString();
comboBox1.Items.Add(sname.ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Pass String into SQL Query from Textbox

Background
I've written a function that retrieves data using a SQL query and then outputs that data to a label. At the moment the search string is hard coded to "1002". The function is fired on a button click event.
Question
How do I pass data into my SQL query from a textbox so my search string is the contents of the text box, instead of 1002?
Code
private void getInfoStationID()
{
String ConnStr = "Data Source=SqlServer; Initial Catalog=Database; User ID=Username; Password=Password";
String SQL = "SELECT stationname FROM dbo.Stations WHERE StationID = 1002";
SqlDataAdapter Adpt = new SqlDataAdapter(SQL, ConnStr);
DataSet question = new DataSet();
Adpt.Fill(question);
foreach (DataRow dr in question.Tables[0].Rows)
{
nameTtb.Text += question.Tables[0].Rows[0]["stationname"].ToString();
}
}
Change the query to:
string constring = #""; // Declare your connection string here.
String SQL = "SELECT stationname FROM dbo.Stations WHERE StationID = #StationId";
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlCommand command = new SqlCommand(SQL ,con);
and then you have to add parameter to the command object like this:
command .Parameters.Add("#StationId",SqlDbType.NVarChar).Value = textbox.Text;
Now you might be wondering why I have used parameters in the query. It is to avoid SQL Injection.
DataSet ds = new DataSet();
SqlDataAdapter adb = new SqlDataAdapter(command);
adb.Fill(ds);
con.Close();
And now you can iterate like this...
foreach (DataRow row in ds.Tables[0].Rows)
{
}
And you have to initialise the connection object and pass your connection string in it.
You can change your SQL string to use a variable, like #StationID, then add the variable to the query from textbox.text
String SQL = "SELECT stationname FROM dbo.Stations WHERE StationID = #StationID";
SqlCommand cmd = new SqlCommand;
cmd.CommandText = SQL;
cmd.CommandType = CommandType.Text;
cmd.Connection = ConnStr;
cmd.Parameters.AddWithValue("#StationID", Textbox1.Text);
da = new SqlDataAdapter(cmd);
DataSet nds = new DataSet();
da.Fill(nds);
String ConnStr = "Data Source=SqlServer; Initial Catalog=Database; User ID=Username; Password=Password";
string SQL = "SELECT stationname FROM dbo.Stations WHERE StationID = #stationID";
SqlCommand command = new SqlCommand(SQL, ConnStr);
command.Parameters.Add(new SqlParameter("#stationID", SqlDbType.Int));
command.Parameters["#stationID"].Value = textbox.Text;

How to get ID against selected value of Dropdownlist C#

How can I get the ID against the selected value of a DropDownList which is bound with DB?
Then how can I insert this ID into another table?
To get ID code
string query = "Select ID From Table-1 Where Name=" + DropDwonList.SelectedValue;
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
string getId = dr[0].ToString();
DropDownList Binding Code
string query = "Select ID, Name from Table-1";
SqlConnection con = new SqlConnection(conStr);
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
da.Fill(dt);
DropDwonList.DataSource = dt;
DropDwonList.DataTextField = "Name";
DropDwonList.DataValueField = "ID";
DropDwonList.DataBind();
DropDwonList.Items.Insert(0, new ListItem("--Select Name--"));
1) string Id = DropDwonList.SelectedValue;
2) To insert into another table just use a query:
string Id = DropDwonList.SelectedValue;
using (SqlConnection sql = new SqlConnection("Your connection string"))
{
SqlCommand cmd = new SqlCommand();
string query = #"INSERT INTO TABLE2(Column1)
VALUES(" + Id + ")";
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Connection = sql;
sql.Open();
cmd.ExecuteNonQuery();
sql.Close();
}
You should do it this way because you always ensure that you are closing a connection after using it.

Webservice convert from string to System.Data.SqlClient.SqlCommand

I'm trying to get an list of items from some table of SQL Server. I'm doing it with Visual Studio 2010.
That's my code:
static string filter = "25";
DataSet Datos = new DataSet();
SqlConnection MyConnection = default(SqlConnection);
SqlDataAdapter MyDataAdapter = default(SqlDataAdapter);
MyConnection = new SqlConnection("Initial Catalog=MyDataBase;Data Source=MyServer;Integrated Security=false;User ID=SQLUser;Password=SQLPass;");
MyDataAdapter = new SqlDataAdapter("SELECT Comment FROM MyTable WHERE [No_] = "+filter+" , MyConnection);
MyDataAdapter.SelectCommand.CommandType = CommandType.Text;
MyDataAdapter.Fill(Datos);
MyDataAdapter.Dispose();
MyConnection.Close();
I'm getting this error:
Argument 1: cannot convert from 'string' to 'System.Data.SqlClient.SqlCommand'
On this line:
MyDataAdapter = new SqlDataAdapter("SELECT Comment FROM MyTable WHERE [No_] = "+filter+" , MyConnection);
So, how can I put the string into my SqlConnection?
Thanks in advance.
This works for me:
string filter = "10";
DataSet Datos = new DataSet();
string connectionString = "<your connection string here>";
string selectCommand =
"SELECT * FROM myTable WHERE Id = " + filter;
using (var MyConnection = new SqlConnection(connectionString))
using (var MyDataAdapter = new SqlDataAdapter(selectCommand, MyConnection))
{
MyDataAdapter.SelectCommand.CommandType = CommandType.Text;
MyDataAdapter.Fill(Datos);
}
This is basically your code, with the using syntax. Give this a try and post if you still have problems. Good luck!

Categories

Resources