C# Insert data to dabase not working - c#

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

Related

ToString argument is wrong

I would like to get some help : I can't get values form SQL Database to WPF textbox.
I tried by myself many codes that didn't worked, and this one looks fine but ".ToString" argument is wrong.
What should i put instead ?
using (SqlConnection con = new SqlConnection(MyConnString))
{
SqlCommand sqlCmd = new SqlCommand("SELECT DATE_A FROM Donnees_Accueil", con);
con.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
hourA.Text = sqlReader["Date_A"].ToString;
}
sqlReader.Close();
}
Thank you in advance,
Zancrew.
Well, ToString() is a method, not property, that's why () is required; if you want to concat all the records:
using (SqlConnection con = new SqlConnection(MyConnString))
{
con.Open();
using (SqlCommand sqlCmd = new SqlCommand("SELECT DATE_A FROM Donnees_Accueil", con))
{
using (SqlDataReader sqlReader = sqlCmd.ExecuteReader())
{
StringBuilder sb = new StringBuilder();
while (sqlReader.Read())
{
sb.Append(Convert.ToString(sqlReader["Date_A"]));
}
hourA.Text = sb.ToString();
}
}
}
If you want to get the 1st record only:
using (SqlConnection con = new SqlConnection(MyConnString))
{
con.Open();
using (SqlCommand sqlCmd = new SqlCommand("SELECT DATE_A FROM Donnees_Accueil", con))
{
using (SqlDataReader sqlReader = sqlCmd.ExecuteReader())
{
if (sqlReader.Read())
hourA.Text = Convert.ToString(sqlReader["Date_A"]);
else
hourA.Text = "";
}
}
}

Getting a query result into a Variable then passing it to a command

Here is my code. I am trying to get a result of a SQL query stored in query1 variable, and want to use that result in a SQL query stored in query variable. Messagebox is irrelevant, I just wrote it to see if I am getting the correct results from listbox1 or not.If i hardcode the query1's result into command parameters, it works perfectly.
private void btnAddCoarse_click(object sender, EventArgs e)
{
MessageBox.Show(listBox1.SelectedItem.ToString());
string query1 ="SELECT ogrenciNo FROM ders,ogrenci,Enrollment WHERE ogrenciId=ogrenciNo AND dersId=dersKodu AND ogrenci.email='" + mainform.Username + "' AND Enrollment.dersId='"+listBox1.SelectedValue+"'";
string query = "INSERT INTO Enrollment(dersId,ogrenciId) VALUES (#dersId, #ogrenciId)";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("#dersId", listBox1.SelectedValue);
command.Parameters.AddWithValue("#ogrenciId",//this is where i need the query1//);
command.ExecuteNonQuery();
PopulateList2();
}
}
You only need one sql command. The structure would be like this:
insert into table2
(field1, field2)
select value1, value2
etc
int id;
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query1, connection))
{
connection.Open();
id = Convert.ToInt32(command.ExecuteScalar()); //I guess it returns only 1 id?..
}
Try doing this
private void btnAddCoarse_click(object sender, EventArgs e)
{
//MessageBox.Show(listBox1.SelectedItem.ToString());
string query1 ="SELECT ogrenciNo FROM ders,ogrenci,Enrollment WHERE ogrenciId=ogrenciNo AND dersId=dersKodu AND ogrenci.email='" + mainform.Username + "' AND Enrollment.dersId='"+listBox1.SelectedValue+"'";
string query = "INSERT INTO Enrollment(dersId,ogrenciId) VALUES (#dersId, #ogrenciId)";
using (connection = new SqlConnection(connectionString))
{
int result=0;
using (SqlCommand command = new SqlCommand(query1, connection))
{
connection.Open();
result=Convert.ToInt32(command.ExecuteScalar());
connection.Close();
}
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("#dersId", listBox1.SelectedValue);
command.Parameters.AddWithValue("#ogrenciId",result);
command.ExecuteNonQuery();
PopulateList2();
}
}
}

Error Trying To Fill Data Table

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

get data from database and display it in gridview (asp.net)

I have a database (SQL server) and I added it into my webpage project but the problem is I cannot display the data in a gridview.
Here is my code:
string query;
SqlCommand SqlCommand;
SqlDataReader reader;
int sindex=DropDownList1.SelectedIndex+1;
int hindex =DropDownList3.SelectedIndex+1;
SqlDataAdapter adapter = new SqlDataAdapter();
//Open the connection to db
conn.Open();
query = string.Format("select * from table where clumn='"+s+"' ", s);
SqlCommand = new SqlCommand(query, conn);
adapter.SelectCommand = new SqlCommand(query, conn);
reader = SqlCommand.ExecuteReader();
GridView2.DataSource = reader;
GridView2.DataBind();
Change this
query = string.Format("select * from table where clumn='"+s+"' ", s);
to this
query = string.Format("select * from table where clumn='{0}' ", s);
Use SqlParameters instead of manipulating a string as you are doing now.
Also, use using statement to dispose objects correctly.
Don't use select * because it will affect performance, only select the columns needed.
Here an example of your code, modified:
using (SqlConnection conn = new SqlConnection(yourConnectionString))
{
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.Text;
command.CommandText = "select column, column2 from table where column=#column";
command.Parameters.Add(new SqlParameter("column", SqlDbType.VarChar, 50));
command.Parameters["column"].Value = yourColumnValue;
conn.Open();
using (SqlDataReader sdr = sco.ExecuteReader())
{
GridView2.DataSource = sdr;
GridView2.DataBind();
}
}
better use SqlDatadapter:
DataTable dt = new DataTable();
...
using (SqlDataAdapter a = new SqlDataAdapter( new SqlCommand(query, conn)))
{
GridView2.DataSource =a.Fill(dt).AsDataView();
}

Not able to fetch data in asp.net c#

protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\ExportPagetoPDFinASP.Net\App_Data\abcc.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM cookbook";
cmd.Connection = con;
cmd.ExecuteReader();
}
Not able to fetch data. i don't know what is wrong.
ExecuteReader would return you a DataReader, you need to iterate it and get rows from your command.
You can also use a DataTable to fill the rows from DataReader like:
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
You can have the following code:
using (SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\ExportPagetoPDFinASP.Net\App_Data\abcc.mdf;Integrated Security=True;User Instance=True"))
{
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT * FROM cookbook";
cmd.Connection = con;
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
}
}
Consider using using statement with your Connection and Command objects.
You can iterate rows returned from DataReader like:
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0])); //prints first column
}
public string Log(int userResult)
{
string result = "result saved";
using (var conn = new SqlConnection("Data Source=XXXX;InitialCatalog=XXXX;Integrated Security=True"))
{
using (var cmd = new SqlCommand())
{
cmd.CommandText = "dbo.setCalculatorResult";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("RESULT", userResult);
if (conn.State != ConnectionState.Open)
conn.Open();
int rowCount = cmd.ExecuteNonQuery();
if (rowCount == 0)
result = "there was an error";
}
}
return result;
}
and also consider using procs

Categories