Unable to add data into database - sql-server-2008

I created a 8 column table in SQL Server 2008. I entered data into 1st 2 column of the table and remaining columns I left allow nulls.
I am trying to add data to remaining 6 columns based on the data entered in 1st 2 columns, but I'm not able to add the data. Was leaving another 6 columns into "Allow nulls" caused this problem.
If yes, is there any solution for this?
Thanks.
string str = (#"Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");
try
{
String sql = "(insert into usn (firstname, lastname, password, address, bloodgrp, contactnum, email) values (#st1, #st2, #st3, #st4, #st5, #st6, #st7) WHERE usn = '" + omd + "' )";
SqlConnection conn = new SqlConnection(str);
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
{
cmd.Parameters.AddWithValue("#st1", TextBox1.Text);
cmd.Parameters.AddWithValue("#st2", TextBox2.Text);
cmd.Parameters.AddWithValue("#st3", TextBox3.Text);
cmd.Parameters.AddWithValue("#st4", TextBox10.Text);
cmd.Parameters.AddWithValue("#st5", TextBox6.Text);
cmd.Parameters.AddWithValue("#st6", TextBox7.Text);
cmd.Parameters.AddWithValue("#st7", TextBox8.Text);
cmd.ExecuteNonQuery();
Response.Redirect("accountcreated.aspx");
conn.Close();
}

If you already have records in your table, you need to use UPDATE, not INSERT.
So, your query should be something like
UPDATE usn
SET firstname = #st1,
lastname = #st2,
password = #st3,
address = #st4,
bloodgrp = #st5,
contactnum = #st6,
email = #st7
WHERE usn = ...
You can't INSERT into a column, you use INSERT only to put data into a table (creating a record).
So, your sql String should look something like this.
String sql = "(UPDATE usn SET firstname = #st1, lastname = #st2, password = #st3, address = #st4, bloodgrp = #st5, contactnum = #st6, email = #st7 WHERE usn = '" + omd + "' )";

Related

Request.form returns value with comma

When I run this code:
string MySQL = "Select * From RegisterDatabase Where uName = '" + Request.Form["username"] +"'";
It didn't work for me, so I tried to see what the problem was and it turns out there's a comma in MySQL.
Select * From RegisterDatabase Where uName = 'Test,'
How do I fix this?
Your code is prone to SQL Injection attack.
You want to parameterized query like this -
string query = "Select * From RegisterDatabase Where uName = #username";
// Remove "," from username
string username = Request.Form["username"].ToString().Replace(",", "");
MySqlCommand command = new MySqlCommand(query);
command.Parameters.AddWithValue("#username", username);
Or some use ?username instead of #username.
Use following
Request.Form["username"].ToString().Replace(',',' ').Trim();

inserting reservation to database

This has been driving me crazy and I'm sure it's something simple. I'm getting a 'values must contain at least one element' error from server when I try to input a reservation from the table that comes up. It's all running ok. No matter if I use quotes in the VALUES section or plus(+)symbols or quotes over the separating commas I get different error messages. When I put quotes over table_num I get and error telling me that you cant insert CHAR into INTEGER. When I remove quotes I get error telling me -
Severe: java.sql.SQLSyntaxErrorException: Column 'TABLE_NUM' is either not in any table in the FROM list or appears within a join specification etc. Could anyone tell me what is going on? Here's the jsp code. Thanks in advance.
<%
int tableNum = 0;
String firstName = null;
String lastName = null;
String Address = null;
int Phone = 0;
java.sql.Date date = null;
int People = 0;
if (request.getParameter("table_num")!=null){
tableNum = Integer.parseInt(request.getParameter("table_num"));
}
if (request.getParameter("first")!=null){
firstName = request.getParameter("first");
}
if (request.getParameter("last")!=null){
lastName = request.getParameter("last");
}
if (request.getParameter("address")!=null){
Address = request.getParameter("address");
}
if (request.getParameter("phone")!=null){
Phone = Integer.parseInt(request.getParameter("phone"));
}
if (request.getParameter("date")!=null){
java.util.Date utilDate = new java.util.Date(request.getParameter("date"));
date = new java.sql.Date(utilDate.getTime());
}
if (request.getParameter("people")!=null){
People = Integer.parseInt(request.getParameter("people"));
}
if(tableNum != 0 && firstName != null && lastName != null && Address != null && Phone != 0 && date != null && People != 0){
String URL = "jdbc:derby://localhost:1527/Reservations";
String USERNAME= "johnpaul";
String PASSWORD= "purlease";
Connection myCon = null;
Statement ste = null;
PreparedStatement preparedStmt = null;
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
System.out.println("Connecting to DB...");
Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/Reservations","johnpaul", "purlease");
System.out.println("Connected successfuly");
System.out.println("Inserting records into table");
Statement st = con.createStatement();
String query = "INSERT INTO JOHNPAUL.CUSTOMER_RESERVATIONS(TABLE_NUM,FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE,DATE,NUMBER_IN_PARTY)VALUES(table_num,first,last,address,phone,date,people)";
st.executeUpdate (query);
System.out.println("Records inserted");
}catch(SQLException se){
se.printStackTrace();
}catch(ClassNotFoundException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
}
%>
Your problem appears to be here:
String query = "INSERT INTO JOHNPAUL.CUSTOMER_RESERVATIONS
(TABLE_NUM, FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE, DATE, NUMBER_IN_PARTY)
VALUES (table_num, first,last,address,phone,date,people)";
Two things here:
1. Escape your strings; and
2. Concatenate the values in your variables to the string.
String query = "INSERT INTO JOHNPAUL.CUSTOMER_RESERVATIONS
(TABLE_NUM, FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE, DATE, NUMBER_IN_PARTY)
VALUES (" + table_num + ", '" + first + "', '" + last + "', '" + address + "', " + phone + " , '" + date + "', " + people + ");";
You may have to verify the format that your database engine expects the date field.

asp.net with mysql Unknown column in where clause

enter code here string customerName = Request.Form[txtSearch.UniqueID];
string customerId = Request.Form[hfCustomerId.UniqueID];
Label1.Enabled = true;
Label1.Text = customerName;
DataRow dr = GetData("SELECT * FROM actor where first_name = " +txtSearch.Text.ToString() ).Rows[0];
Document document = new Document(PageSize.A4, 88f, 88f, 10f, 10f);
Font NormalFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, Color.BLACK);
Is there any problem with mysql syntax?
Correct me if i am going wrong.
While i am searching with a specified value, this runs perfectly. But creating problem when trying to pass a value.
try this:
DataRow dr = GetData("SELECT * FROM actor where first_name = '" +txtSearch.Text+"' ).Rows[0];

Using JDBC template, How can I update a column in every customer in a mysql database?

So, I am trying to create a function that when called updates the lastEmailed column for every customer in the database called customers, but I can't seem to find out an approach that seems to work. Any help would be greatly appreciated! Also, the input style is in the format 2014-12-09 14:20:47 (datetime). ** this is a NamedParameterJdbcTemplate.
public void updateTime(String timeSent){
// String query = "UPDATE customers SET lastEmailed ='" + timeSent+"'";
// String query = "UPDATE customers SET lastEmailed = ?";
// String query = "INSERT INTO CUSTOMERS "
// this.jdbcTemplate.
// this.jdbcTemplate.execute(query);
// this.jdbcTemplate.update
// SqlParameterSource [] parameterSource = SqlParameterSourceUtils.createBatch(this.getCustomerList().toArray());
// this.jdbcTemplate.batchUpdate("INSERT INTO CUSTOMERS (id,lastEmailed) VALUES (:customerNumber, " +timeSent + ")", parameterSource);

having problems with mysql statement where and or based on user input

$query = "SELECT username, email, password, salt
FROM tbl_memembers
WHERE (username = $resetuser) OR (email = $resetuser)";
This keeps returning that there is nothing in the database, when I know for a fact that there is matching those details entered ($resetuser = $_POST from previous page)
Try with this query
$query = "SELECT username, email, password, salt
FROM tbl_memembers
WHERE username = '$resetuser' email = '$resetuser' ";
Is there a table namned 'tbl_memembers' or should it be 'tbl_members'? As #Abhik Chakraborty points out - the parameters should be surrounded by ''. Then again - shouldn't '' just declare $resetuser as a string, not the parameter name? I'm a .NET-developer and have no experience of PHP but in .NET any parameter must be surrounded by username = '" & parametername & "'.