Insert statement on asp.net not inserting on mysql table - c#

I am creating a web form on asp.net that will allow the end user to assign multiple users bassed on a selected department to a quiz..
the database is mysql database since I use joomla
the tables on mysql are: jos_users_quizzes with the following columns:
id
quiz_id
user_id
I have a second is called called
jos_dhruprofile with this columns
id
name
username
department
I need to select all user ids from selected department and insert those id into the user_quizzes table.
I have two queries trying to to insert the first one which has the condition for selected department doesnt work while
the one without the were statement actually inserts, I get no errors , just the insertion doesnt go..
string quizidselected = DropDownList1.SelectedValue;
string deptselected = ListBox2.SelectedValue;
OdbcCommand cmd = new OdbcCommand("INSERT INTO jos_jquarks_users_quizzes (user_id, quiz_id) SELECT uid, ' " + quizidselected + " ' FROM jos_dhruprofile WHERE department = ' " + deptselected.ToString() + " '");
// OdbcCommand cmd = new OdbcCommand("INSERT INTO jos_jquarks_users_quizzes (user_id, quiz_id) SELECT uid, ' " + quizidselected + " ' FROM dhruprofile ");
THANKS IN ADVANCE FOR LOOKING MY CODE
Full code
Code from and ASP.NET form to insert ....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Text;
using System.Data;
using System.Data.Odbc;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private void InsertRecords(StringCollection sc)
{
string ConnectionString = #"driver={MySQL ODBC 5.1 Driver};server=appdevelsvr;database=xxxx;uid=xx;pwd=xx;";
OdbcConnection conn = new OdbcConnection(ConnectionString);
try
{
conn.Open();
string quizidselected = DropDownList1.SelectedValue;
string deptselected = ListBox2.SelectedValue;
OdbcCommand cmd = new OdbcCommand("INSERT INTO jos_jquarks_users_quizzes (user_id, quiz_id) SELECT uid, ' " + quizidselected + " ' FROM jos_dhruprofile WHERE department = ' " + deptselected.ToString() + " '");
// OdbcCommand cmd = new OdbcCommand("INSERT INTO jos_jquarks_users_quizzes (user_id, quiz_id) SELECT uid, ' " + quizidselected + " ' FROM dhruprofile ");
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
Response.Write(deptselected.ToString());
// Response.Write(sql.ToString());
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
StringCollection sc = new StringCollection();
foreach (ListItem item in ListBox2.Items)
{
if (item.Selected)
{
sc.Add(item.Text);
}
}
InsertRecords(sc);
}
}

I am assuming that the query you want us to debug is the one with the where clause.
Please set a breakpoint at the line where you are creating a new odbc command for cmd. You need to check the value of 'deptselected'.
Alternatively, you can debug.writeline the SQL statement and copy-paste it into a SQL query UI. Please run the select by itself. I think it will not return any rows because either 'deptselected' doesn't exist in your table or 'deptselected' is empty.
Also, two good programming pointers:-
1). Use parameterized SQL statements instead of appending values into the string. Your code is vulnerable to a SQL injection attack. This is very bad.
2). 'deptselected' is already a string, you do not need to 'ToString' it again.
Hope this helps.
Edit:-
I just read the comments above. Do a select * (star) on that table and where someother_column = another_value to get the same row that you are interested in. Check the string lenght of your department column. Check if you have spaces at the beginning of the string or after.

Related

ASP.NET SqlDataReader Incorrect syntax near

I've had an ASP.NET page that had worked for quite a while, up until recently. The page contains a single text box (TextBox1) and a submit button. When you input (or scan) a number into the field and submit it, if the record exists in the database and hasn't been submitted before, it adds a date/time stamp to another column and gives the user feedback that it's been recorded. If the record exists and already had a date/time stamp, it doesn't change anything but gives the user feedback that the record already has been input or scanned. If the record doesn't exist, it gives the user feedback that there is no such record.
This all worked fine when I was inputting numerical values. Now, the numeric values have changed to alphanumeric and I'm getting and error. Anytime I input a value that is alphanumeric, I get an
Incorrect syntax near 'x'
error that refers to line 35:
using(SqlDataReader reader = command.ExecuteReader())
My entire code from my aspx.cs file is below. Any suggestions are greatly appreciated!
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
private string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
}
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
try
{
connection.Open();
string sql = #"SELECT PRODUCT_ID from PRODUCTS where PRODUCT_ID = " + TextBox1.Text + " and DATE is null";
using(SqlCommand command = new SqlCommand(sql, connection))
{
using(SqlDataReader reader = command.ExecuteReader())
{
if(reader.HasRows)
{
string sql2 = #"UPDATE [products] SET date=#Value2 where PRODUCT_ID=#Value1";
using (SqlCommand command2 = new SqlCommand(sql2, connection))
{
command2.Parameters.AddWithValue("#Value1", TextBox1.Text);
command2.Parameters.AddWithValue("#Value2", DateTime.Now);
command2.ExecuteNonQuery();
}
pageBody.Attributes.Add("bgcolor", "#9aff8e");
Label1.Text = "Item " + TextBox1.Text + " Recorded!";
TextBox1.Text = "";
}
else
{
reader.Close();
string sql3 = #"SELECT PRODUCT_ID from PRODUCTS where PRODUCT_ID = " + TextBox1.Text + "";
using(SqlCommand command3 = new SqlCommand(sql3, connection))
{
using(SqlDataReader reader2 = command3.ExecuteReader())
{
if (reader2.HasRows)
{
pageBody.Attributes.Add("bgcolor", "#fbff8e");
Label1.Text = "Item " + TextBox1.Text + " Already Shipped!";
TextBox1.Text = "";
}
else
{
pageBody.Attributes.Add("bgcolor", "#ff8e8e");
Label1.Text = "Item " + TextBox1.Text + " Not Found!";
TextBox1.Text = "";
}
}
}
}
}
}
}
finally
{
if(connection.State != ConnectionState.Closed)
{
connection.Close();
}
}
}
}
}
First of all: Never do string concatenation for SQL with user input. It opens up risk for Sql Injection which can destroy your database.
The error is due to the change in datatype of PRODUCT_ID from number to string. Add ' to fix the error.
string sql = #"SELECT PRODUCT_ID from PRODUCTS where PRODUCT_ID = '#Value1' and DATE is null";
using(SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("#Value1", TextBox1.Text);
...
}
I hope since you are inputing a alphanumeric field, you have to use. (Note the quotes beside textbox text )
string sql = #"SELECT PRODUCT_ID from PRODUCTS where PRODUCT_ID = '" + TextBox1.Text + "' and DATE is null";
As you are saying its a alphanumeric field, you have to search your product_id by enclosing it as a string.
(Assuming datatype of PRODUCT_ID in your table is varchar. If your datatype is not VARCHAR, you might still see an error )
And yes, As #Faruq mentioned, make sure to update your code to use command parameters to avoid SQL injections.
Change:
PRODUCT_ID = " + TextBox1.Text + "
TO:
PRODUCT_ID = '" + TextBox1.Text + "'
You need to quote the text, so abc should be 'abc' when it gets to the database.

C# ASP Web Form Logic

Could someone tell me what I'm doing wrong? I've tried to accomplish this in numerous different ways, but have not been able to. Without adding the parameters in, the form runs, but I need the parameters so that I can update records if it so evaluates. I may be off track, so any help is very appreciated.
For example, if a product code is entered and doesn't have a date already, the form should update the date with the current date/time. If the product code does have a date already, it should notify the user that the product has already shipped, else telling the user that the product is not in the database.
It evaluates by querying if there is a product code and if the date is null. If that evaluates to be true, then it should update that product code with a current timestamp in the date column. If that evaluates to be false, it checks to see if the product code exists in the table at all. If it does and the date column is not null, it reports that the product has already shipped, else, it reports that the product doesn't exist in the database.
Without the following parameters, it runs fine, providing the correct responses but, of course, it doesn't ever call to update a record.
command2.Parameters.AddWithValue("#Value1", TextBox1.Text);
command2.Parameters.AddWithValue("#Value2", DateTime.Now);
With these parameters added in, I get an error stating the "The name 'command2' does not exist in the current context. But, I only get this error one. Sorry if my code is way out of line. Thanks in advance for your help!
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
}
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
try
{
connection.Open();
string sql = #"SELECT PRODUCT_ID from PRODUCTS where PRODUCT_ID = " + TextBox1.Text + " and DATE is null";
using(SqlCommand command = new SqlCommand(sql, connection))
{
using(SqlDataReader reader = command.ExecuteReader())
{
if(reader.HasRows)
{
string sql2 = #"UPDATE [products] SET date=#Value2 where PRODUCT_ID=#Value1";
using (SqlCommand command2 = new SqlCommand(sql2, connection))
command2.Parameters.AddWithValue("#Value1", TextBox1.Text);
command2.Parameters.AddWithValue("#Value2", DateTime.Now);
pageBody.Attributes.Add("bgcolor", "#9aff8e");
Label1.Text = "Item " + TextBox1.Text + " Recorded!";
TextBox1.Text = "";
}
else
{
reader.Close();
string sql3 = #"SELECT PRODUCT_ID from PRODUCTS where PRODUCT_ID = " + TextBox1.Text + "";
using(SqlCommand command3 = new SqlCommand(sql3, connection))
{
using(SqlDataReader reader2 = command3.ExecuteReader())
{
if (reader2.HasRows)
{
pageBody.Attributes.Add("bgcolor", "#fbff8e");
Label1.Text = "Item " + TextBox1.Text + " Already Shipped!";
TextBox1.Text = "";
}
else
{
pageBody.Attributes.Add("bgcolor", "#ff8e8e");
Label1.Text = "Item " + TextBox1.Text + " Not Found!";
TextBox1.Text = "";
}
}
}
}
}
}
}
finally
{
if(connection.State != ConnectionState.Closed)
{
connection.Close();
}
}
}
}
}
Put your parameters assignment inside a bracket and don't forget to call the execute method.
using (var command2 = new SqlCommand(sql2, connection))
{
command2.Parameters.AddWithValue("#Value1", TextBox1.Text);
command2.Parameters.AddWithValue("#Value2", DateTime.Now);
command2.ExecuteNonQuery();
}
using (SqlCommand command2 = new SqlCommand(sql2, connection)) {
command2.Parameters.AddWithValue("#Value1", TextBox1.Text);
command2.Parameters.AddWithValue("#Value2", DateTime.Now);
}
Forgot your brackets.

Load data from SQL Server database to C#

I get this error:
System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'Table'.
when I run the program; it said the error near to table!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string SOURCE = #"Data Source=DESKTOP-K39PU4T\SQLEXPRESS;Initial Catalog=Mohamed;Integrated Security=True";
SqlConnection CON = new SqlConnection(SOURCE);
CON.Open();
MessageBox.Show("DB Connected");
string SqlSelectQuery = " Select*From Table Where ID ="+ int.Parse(textBox1.Text);
SqlCommand cmd = new SqlCommand(SqlSelectQuery, CON);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
textBox2.Text = (dr["Name"].ToString());
textBox3.Text = (dr["Surname"].ToString());
textBox4.Text = (dr["Lastname"].ToString());
}
else
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
MessageBox.Show("No Record Found Please Enter Correct Id");
}
CON.Close();
}
}
}
I want to load the data from SQL Server to ASP.NET in Visual Studio
Table is key word, if you have table named "Table" you may need to use [Table] for escape keyword in the SQL string, otherwise give the correct table name instead of Table. also you better use parameters instead of concatenating string as sql statement.
string SqlSelectQuery = "Select * From [Table] Where ID =#ID";
SqlCommand cmd = new SqlCommand(SqlSelectQuery, CON);
cmd.Parameters.AddWithValue("#ID", int.Parse(textBox1.Text));
What is the table name from which you want to get data?
if its name is Table then replace " Select*From Table Where ID =" with " Select * From \"Table\" Where ID ="
otherwise replace Table with actual table name

Creating Database. Why is it not working? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a problem. I want to make a Books database with C# with serialNumber, Author, Name and Year of publishing columns. I did the code and I don't have any errors but when i start it the console is left black and it doesn't do anything. Can someone tell me why it´s not working?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
namespace T4DB1
{
class Program
{
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection("Data Source=localhost; Initial Catalog=master; Integrated Security = True");
{
string create = "if not exists (select * from sys.databases where name='Buecher') create database [Buecher] else begin drop database [Buecher] create database [Buecher] end ";
SqlCommand createDB = new SqlCommand(create, conn);
try
{
conn.Open();
createDB.ExecuteNonQuery();
Console.WriteLine("Database created");
}
catch (Exception ex)
{
Console.WriteLine("Error");
}
finally
{
if (conn.State == System.Data.ConnectionState.Open)
{
conn.Close();
}
}
conn = new SqlConnection("Data Source = localhost; Initial Catalog=Buecher; Integrated Security = True");
create = " create table Buecher1 ( ISBNNummer varchar(10) not null Primary Key, Autor varchar(40), Titel varchar(50), Erscheinungsjahr smallint)";
createDB = new SqlCommand(create, conn);
try
{
conn.Open();
createDB.ExecuteNonQuery();
Console.WriteLine("Table created");
string insertrow = "insert into Buecher1 (ISBNNummer, Autor, Titel, Erscheinungsjahr) values('2658A42', 'Douglas Adams', 'Galaxy', 2007)";
createDB = new SqlCommand(insertrow, conn);
createDB.ExecuteNonQuery();
string insertrow2 = "insert into Buecher1 (ISBNNummer, Autor, Titel, Erscheinungsjahr) values('58624FG85', 'Charles Dickens', 'White Fang',1992)";
createDB = new SqlCommand(insertrow2, conn);
createDB.ExecuteNonQuery();
string insertrow3 = "insert into Buecher1 (ISBNNummer, Autor, Titel, Erscheinungsjahr) values('65224AS4', 'Erik Corr', 'Somewhere', 2014)";
createDB = new SqlCommand(insertrow3, conn);
createDB.ExecuteNonQuery();
string select = "Select * From Buecher1";
SqlDataAdapter da = new SqlDataAdapter(select, conn);
DataTable dt = new DataTable(); da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
Console.WriteLine("ISBNNummer: " + row["ISBNNummer"] + " " + "Autor: " + row["Autor"] + " " + "Titel: " + row["Titel"] + " " + "Erscheinungsjahr:" + row["Erscheinungsjahr"]);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
if (conn.State == System.Data.ConnectionState.Open)
{
conn.Close();
}
}
}
Console.ReadKey();
}
}
}
I'm assuming you are using SQL Server. Just consider this statement:
if not exists (select * from sys.databases where name='Buecher')
create database [Buecher]
It does not behave as you expect. The command is first compiled. During this phase, if Buecher exists, you'll get an error on create database [Buecher]' because you cannot create a database that already exists. You might protest, "But that is why I have the if!" Too bad. the compiler is not listening. You see the if isn't executed until the execution phase -- after the compile phase.
And, the same is true of the drop.
A typical way to handle this is to use dynamic SQL. That postpones the compilation until the execution. So, this snipper should work:
if not exists (select * from sys.databases where name='Buecher')
exec('create database [Buecher] ');

Asp.net adding database from textbox and dropdownlist

net to adding database. I am trying to do texts on two textbox and one selected value in dropdownlist to add my table.
Here is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = #" Data Source=.\SQLEXPRESS;AttachDbFilename=C:\USERS\CEM\DOCUMENTS\VISUAL STUDIO 2010\WEBSITES\EKLEMEDENE\APP_DATA\DATABASE.MDF;Integrated Security=True;User Instance=True";
string queryString = "INSERT INTO ekle(flight, name, food) VALUES ('" + TextBox1.Text + " ' , '" + TextBox2.Text + " ' , '" + DropDownList1.SelectedValue + " ' )";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(queryString, con);
con.Open();
command.ExecuteNonQuery();
con.Close();
}
}
After I execute I will have error
Database 'C:\Users\Cem\Documents\Visual Studio 2010\WebSites\eklemedene\App_Data\Database.mdf' already exists. Choose a different database name.
An attempt to attach an auto-named database for file C:\USERS\CEM\DOCUMENTS\VISUAL STUDIO 2010\WEBSITES\EKLEMEDENE\APP_DATA\DATABASE.MDF failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
You're wide open for SQL-Injection. Avoid passing parameters directly from controls. Instead use Parameters.
Use using-statement for anything implementing IDisposable like Connections or Commands:
There's something wrong with your ConnectionString, you could try to use SqlConnectionStringBuilder class:
//Build the connection
SqlConnectionStringBuilder bldr = new SqlConnectionStringBuilder();
//Put your server or server\instance name here. Likely YourComputerName\SQLExpress
bldr.DataSource = ".\\SQLEXPRESS";
//Attach DB Filename
bldr.AttachDBFilename = #"C:\USERS\CEM\DOCUMENTS\VISUAL STUDIO 2010\WEBSITES\EKLEMEDENE\APP_DATA\DATABASE.MDF";
//User Instance
bldr.UserInstance = true;
//Whether or not a password is required.
bldr.IntegratedSecurity = true;
using(var connection = new SqlConnection(bldr.ConnectionString))
{
var sql = "INSERT INTO ekle(flight, name, food) VALUES (#flight, #name , #food)";
using(var command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("#flight", TextBox1.Text);
command.Parameters.AddWithValue("#name", TextBox2.Text);
command.Parameters.AddWithValue("#food", DropDownList1.SelectedValue);
connection.Open();
command.ExecuteNonQuery();
}
} // closes the connection implicitely

Categories