This is my syntax, but I get an error of
The SelectCommand property has not been initialized before calling 'Fill'.
what do I need to do in order to be able to fill the data table?
using (SqlConnection conn = new SqlConnection("Server=Test;Database=Test;Integrated Security=SSPI;"))
{
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM [dbo].[selfservice] WHERE saleID = #userid;";
command.Parameters.Add("#userid", SqlDbType.VarChar);
command.Parameters["#userid"].Value = row.Field<string>("saleID");
command.Connection = conn;
using (SqlDataAdapter dataadapter1 = new SqlDataAdapter()
{
dataadapter1.Fill(dtData);
}
}
Notice that you're not using the command object. You need to add the select command to your adapter:
using (SqlDataAdapter dataadapter1 = new SqlDataAdapter()
{
dataadapter1.SelectCommand = command
dataadapter1.Fill(dtData);
}
you have to specify select command of SqlDataAdapter before Fill, also you are missing a close parenthesis at the end
using (SqlDataAdapter dataadapter1 = new SqlDataAdapter())
{
dataadapter1.SelectCommand=command;
dataadapter1.Fill(dtData);
}
Related
I'm trying to show in my datagridview all the registers from a mariadb database, but when I start the code, it appears the errror "Connection must be valid and open error", the code is Here:
I'll be glad if somebody can help me :)
There are two main problems with your code. Firstly you don't associate your connection object with your command object, instead of
MySqlCommand cmd = new MySqlCommand("SELECT * FROM encomendas");
It should be
MySqlCommand cmd = new MySqlCommand("SELECT * FROM encomendas", bdcon);
Also, there is no need to call cmd.ExecuteNonQuery(). It is also advisable to use using blocks on objects that implement IDisposable to ensure they are disposed of correctly, so your full code might be:
var datatable = new DataTable();
using (var connection = new MySqlConnection("connectionstring"))
using (var command = new MySqlCommand("SELECT * FROM encomendas", connection ))
{
connection.Open()'
using (var reader = command.ExecuteReader())
{
datatable.Load(reader);
}
}
// Bind to your grid view
With that being said, if you are looking to fill a DataTable then MySqlDataAdapater() is the simplest approach:
var dt = new DataTable();
using (var adapter = new MySqlDataAdapter("SELECT * FROM encomendas", "ConnectionString"))
{
adapter.Fill(dt);
}
// Bind to your grid view
Delete MysqlCommand cmd = new MySqlCommand("") row and
try it
using (var sqlCommand = new MySqlCommand("SELECT * FROM encomendas", bdcon))
{
MySqlDataReader read = sqlCommand.ExecuteReader();
dt.Load(read);
}
try it
Your object of MysqlCommand must have association with your object MysqlConnection. Obviously your cmd has no business with bdcon, that is the reason why it says "Connection must be valid and open error" when you call the method ```cmd.ExecuteNonQuery().
Here is a similar snippet.
SqlConnection sqlConnection = new SqlConnection();
SqlCommand cmd = sqlConnection.CreateCommand();
//or
SqlCommand cmd = new SqlCommand("sql text", sqlConnection);
I am super newbie with Visual Studio. I want to create an application form in Visual Studio to insert data into my T-SQL database.
I have created a very simple Windows Application Form. It takes data from fields and insert them into my database. it simple and it works.
Now, what i want to do is to add the function for the app to look if values already exists in the database, so it wont create duplicates.
What im looking for to be checked is first_name, last_name and dob.
as im super newbie, i added an if statement to the Submit button (on click) like below:
private void btnSubmit_Click(object sender, EventArgs e)
{
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("UserInterface", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
if (txtFirstName == sqlCmd.CommandText("EXISTS first_name FROM employee"))
MessageBox.Show("already exists");
}
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("UserInterface", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#first_name", txtFirstName.Text.Trim());
sqlCmd.Parameters.AddWithValue("#last_name", txtLastName.Text.Trim());
sqlCmd.Parameters.AddWithValue("#dept_id", txtDepartmentID.Text.Trim());
sqlCmd.Parameters.AddWithValue("#job_title", txtJobTitle.Text.Trim());
sqlCmd.Parameters.AddWithValue("#dob", dateDOB.Text);
sqlCmd.Parameters.AddWithValue("#start_date", dateStartDate.Text);
sqlCmd.Parameters.AddWithValue("#contract_type", txtContractType.Text.Trim());
sqlCmd.Parameters.AddWithValue("#status_code", txtStatusCode.Text.Trim());
sqlCmd.Parameters.AddWithValue("#effect_date", dateEffectDate.Text);
sqlCmd.ExecuteNonQuery();
MessageBox.Show("Insertion Successful");
Clear();
}
}
void Clear()
{
txtFirstName.Text = txtLastName.Text = txtJobTitle.Text = txtDepartmentID.Text = txtContractType.Text = txtStatusCode.Text = "";
dateDOB.Text = dateEffectDate.Text = dateStartDate.Text = "";
}
obviously I'm very new and it does not work.
How can i go ahead and do this?
A few things to mention on this portion:
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("UserInterface", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
if (txtFirstName == sqlCmd.CommandText("EXISTS first_name FROM employee"))
MessageBox.Show("already exists");
}
A SqlCommand object can have several command types, 2 of which are CommandType.StoredProcedure (which you used to insert your new records) and CommandType.Text which is used to supply plain SQL directly. For this case you want to set it as plain text so change that line to:
sqlCmd.CommandType = CommandType.Text;
The first parameter of the constructor of the SqlCommand is the command text. If the command is gonna be a stored procedure call, then you need to pass the SP name (which you've done when inserting your new row), but if you want plain SQL then you can write it here (I modified the SQL to actually search for the first name in a safe way, preventing SQL Injection):
SqlCommand sqlCmd = new SqlCommand("SELECT first_name FROM employee WHERE first_name = #firstName", sqlCon);
DbParameter firstNameParameter = new SqlParameter("#firstName", txtFirstName.Text.Trim());
sqlCmd.Parameters.Add(firstNameParameter);
You need to execute the command with the ExecuteReader() method, and this will return a reader object you need to use to retrieve it's results (the SQL might return several rows).
using (DbDataReader reader = sqlCmd.ExecuteReader())
while (reader.Read())
{
MessageBox.Show("already exists");
break;
}
This is a head-start so you can keep on coding, many things to improve yet but might be too much if explained all of a sudden.
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
SqlCommand sqlCmd = new SqlCommand("SELECT first_name FROM employee WHERE first_name = #firstName", sqlCon);
DbParameter firstNameParameter = new SqlParameter("#firstName", txtFirstName.Text.Trim());
sqlCmd.Parameters.Add(firstNameParameter);
sqlCmd.CommandType = CommandType.Text;
sqlCon.Open();
using (DbDataReader reader = sqlCmd.ExecuteReader())
while (reader.Read())
{
MessageBox.Show("already exists");
break;
}
}
I have a connection to a database set up like this to call a stored procedure. I am just wondering if this is the best way to do this.
I have two using statements one for the sqlConnection and one for the sqlCommand (which I am not really sure if its needed)
using (SqlConnection con1 = new SqlConnection(conString1))
{
using (SqlCommand cmd1 = new SqlCommand())
{
cmd1.Connection = con1;
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.CommandText = "updateVendorEstNo";
cmd1.Parameters.AddWithValue("#plantNameNew", vPlantName.Value.ToString().Trim());
var result = cmd1.Parameters.Add("#result", SqlDbType.Int);
result.Direction = ParameterDirection.Output;
var resultDesc = cmd1.Parameters.Add("#resultDesc", SqlDbType.VarChar, 100);
resultDesc.Direction = ParameterDirection.Output;
con1.Open(); // open connection
cmd1.ExecuteNonQuery();
res = result.Value.ToString().Trim();
resDesc = resultDesc.Value.ToString().Trim();
}
}
My biggest question is when I am doing :
using (SqlCommand cmd1 = new SqlCommand())
Is it fine the way it is done right now.. or should it be more like,
using (SqlCommand cmd1 = new SqlCommand("updateVendorEstNo",con1))
I think that the way you have it is fine, because the using statement will ensure that the object is disposed of either way.
can you tell me why this code is not inserting anything in my database? I have some troubles, I'm new.
private void reserveButton()
{
string query = "INSERT INTO Rezervari VALUES (#nume, #rand, #coloana, #data, #film, #tipBilet)";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
connection.Open();
command.Parameters.AddWithValue("#nume", textBox1.Text);
command.Parameters.AddWithValue("#rand", comboBox1.SelectedValue);
command.Parameters.AddWithValue("#coloana", comboBox2.SelectedValue);
command.Parameters.AddWithValue("#data", listBox2.SelectedValue);
command.Parameters.AddWithValue("#film", listBox1.SelectedValue);
command.Parameters.AddWithValue("#tipBilet", listBox4.SelectedValue);
command.ExecuteNonQuery();
}
MessageBox.Show("Ticket Reserved. See you at the movies!");
}
string query = "INSERT INTO Rezervari (ColumnName1,ColumnName2)
VALUES (#ColumnName1,#ColumnName2)";
var connection = new SqlConnection(connectionString);
var command = new SqlCommand(query, connection);
connection.Open();
command.Parameters.AddWithValue("#ColumnName1", "aaaa");
command.Parameters.AddWithValue("#ColumnName2", "bbbb");
command.ExecuteNonQuery();
con.Close();
}
Instead of ColumnName1 please write your Column Name
I am calling the following code in C# to fill a dataAdapter with a given stored procedure "sp1_name". The problem is that I want to call different stored procedures with different parameters. (All SP's do a SELECT)
Let's suppose that my stored procedure name is "SP_SOMESP", then everything works fine.
Let's suppose that my stored procedure name is "SP_SOMESP #Month= 10, #Year = 2010", then it doesn't work. It throws an exception that cannot find this stored procedure.
Any solutions?
Thanks!
//First Connection - SP1
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sp1_name, con)) //sp1_name = NAME + PARAMETERS
{
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
{
dataAdapter.Fill(results2);
}
}
}
First Issue:
Parameters in a stored procedure shouldn't be included along with its name
Second Issue:
Having a space in names of stored procedure isn't a good practice.
And for code behind
using(SqlConnection con = new SqlConnection("Your Connection String Here"))
{
SqlCommand cmd = new SqlCommand("sp_SomeName", con);
cmd.CommandType = CommandType.StoredProcedure;
//the 2 codes after this comment is where you assign value to the parameters you
//have on your stored procedure from SQL
cmd.Parameters.Add("#MONTH", SqlDbType.VarChar).Value = "someValue";
cmd.Parameters.Add("#YEAR", SqlDbType.VarChar).Value = "SomeYear";
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataSet ds = new SqlDataSet();
da.Fill(ds); //this is where you put values you get from the Select command to a
//dataset named ds, reason for this is for you to fetch the value from DB to code behind
foreach(DataRow dr in ds.Tables[0].Rows) // this is where you run through the dataset and get values you want from it.
{
someTextBox.Text = dr["Month"].ToString(); //you should probably know this code
}
}
You have to add in the parameters programmatically, see SqlCommand.Parameters.
It would be something like
cmd.Parameters.AddWithValue("#Month", 10);
cmd.Parameters.AddWithValue("#Year", 2010);
This would be after the command is declared and before it is executed.
If you find that you need to delcare the data type, then try it this way
cmd.Parameters.Add("#Month", SqlDbType.Int).Value = 10;
Check this,
using (SQLCommand cmd = new SQLCommand())
{
cmd.CommandText = "SP_SOMESP";
cmd.Parameters.Add("#Month", 10);
cmd.Parameters.Add("#Year", 2010);
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
}
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
{
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(results2);
}