Webservice convert from string to System.Data.SqlClient.SqlCommand - c#

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!

Related

How to search between 2 dates on access database vs?

I'm trying this code but it shows an error on da.Fill(dt)
No value given for one or more required parameters.
Why does it show that error? I clearly check all names of databases and tables and fields, they all are correct and I'm using date/time field for datetime.
Can you help me with this?
string conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ahmed\OneDrive\Documents\shop.accdb";
OleDbConnection ccc = new OleDbConnection(conn);
ccc.Open();
string css = "SELECT * from tbl3 Where dateitem between '" + dateTimePicker1.Value.ToString() + "%' AND '" + dateTimePicker2.Value.ToString()+"%'";
OleDbCommand non = new OleDbCommand(css, ccc);
OleDbDataAdapter da = new OleDbDataAdapter(non);
DataTable dt = new DataTable();
da.Fill(dt);
count = Convert.ToInt32(dt.Rows.Count.ToString());
dataGridView1.DataSource = new BindingSource(dt, null);
As others have mentioned you should use the parameters instead of hard coding the values.
using (OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ahmed\OneDrive\Documents\shop.accdb"))
{
conn.Open();
// DbCommand also implements IDisposable
using (OleDbCommand cmd = conn.CreateCommand())
{
var param1 = new OleDbParameter("#DateTimePicker1", OleDbType.DBDate); //you may have to play with different types
param1.Value = dateTimePicker1.Value;
cmd.Parameters.Add(param1);
var param2 = new OleDbParameter("#DateTimePicker2", OleDbType.DBDate);
param2.Value = dateTimePicker2.Value;
cmd.Parameters.Add(param2);
cmd.CommandText = "SELECT * from tbl3 Where datetime >= #DateTimePicker1 and datetime <= #DateTimePicker2";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
count = Convert.ToInt32(dt.Rows.Count.ToString());
dataGridView1.DataSource = new BindingSource(dt, null);
}
}

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;

Why doesn't my dataset fill?

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();

How to pass dataset through query

I need to get a database values to the p_cat combo box .....but i cannot pass the dataset inside the query..
class Datatbl_Class1
{
DataSet ds = new DataSet();
public DataSet filldata(string q)
{
string myconnection = "datasource=localhost;port=3306;username = root; password = 12345V";
MySqlConnection con = new MySqlConnection(myconnection);
MySqlCommand cmd = new MySqlCommand(q, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(ds);
return ds;
}
}
Select_int_Class1 s4 = new Select_int_Class1();
string q = "SELECT Sup_ID FROM gtec_computer.supplier WHERE Sup_Name='" +p_cmb_sup.Text+ "'";
string ww = "Sup_ID";
int t = s4.select_val_int(q, ww);
DataSet n = new DataSet();
Datatbl_Class1 dt = new Datatbl_Class1();
string Query = "SELECT Cat_ID FROM gtec_computer.supplier_detail WHERE Sup_Id="+t+" ";
n = dt.filldata(Query)
DataSet ds = new DataSet();
string myconnection = "datasource=localhost;port=3306;username = root; password = 12345V";
MySqlConnection con = new MySqlConnection(myconnection);
string q1 = "SELECT cat_Name FROM gtec_computer.category WHERE Cat_ID= " + n + " ";
MySqlCommand cmd = new MySqlCommand(q1, con);
MySqlDataAdapter da1 = new MySqlDataAdapter(cmd);
da1.Fill(ds);
p_cat.DataSource = ds;
You should be able to via parameter to the function call in the class... However, by building your command strings, you would be wide open for SQL-injection. Look into parameterized queries. Now, back to your original code and an alternative implementation...
class Datatbl_Class1
{
public DataSet filldata(string q )
{
string myconnection = "datasource=localhost;port=3306;username = root; password = 12345V";
MySqlConnection con = new MySqlConnection(myconnection);
MySqlCommand cmd = new MySqlCommand(q, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ReturnThisOne = new DataSet();
da.Fill(ReturnThisOne);
return ReturnThisOne;
}
}
Just dont make the "ds" as a property of the class. Just create a new instance of a dataset within your method. It will be a pointer anyhow. Fill that and return the pointer to the calling source as you already are doing with your "n = dt.filldata(Query)". Yes, the function is no longer using the data table, but since it's reference is being returned, then the "n" location that is calling it will retain it. It won't get released to garbage collection until the function that "n" is in gets released.
Again, look into parameters to prevent sql-injection. But this should get you going.

dynamic binding of chart from database in VS2010 in C#

I have to create charts with dynamic datasource, I have a code. It does not show error but the graph is also not visible on runtime.
Here out_table is the name of my table and ADX is one of its column.
code:
OleDbConnection con1 = new OleDbConnection(#"PROVIDER=Microsoft.ACE.OLEDB.12.0;DATA SOURCE=RS.accdb");
String sqlo = "Select ADX from " + out_table + "";
OleDbCommand myCommand = new OleDbCommand(sqlo, con1);
myCommand.Connection.Open();
OleDbDataReader myreader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
chart1.DataBindTable(myreader, "ADX");
thanks for helping me. I have solved this problem, and for others, here is the solution.
here, ds is dataset
OleDbConnection con1 = new OleDbConnection(#"PROVIDER=Microsoft.ACE.OLEDB.12.0;DATA SOURCE=RS.accdb");
String sqlo = "Select * from " + out_table + "";
OleDbDataAdapter da1 = new OleDbDataAdapter(sqlo, con);
DataSet ds = new DataSet();
da1.Fill(ds, in_table);
DataView firstView = new DataView(ds.Tables[0]);
chart1.Series[0].Points.DataBindXY(firstView, "ID", firstView, "ADX");

Categories

Resources