How to insert data taken from user into mysql using jdbc - mysql

I'd like to get a data (e.g. name) from user and insert it into mysql using JDBC.
I'm trying to do something like this:
String uName = Username.getText(); (where uName is the name of the texfield)
Then I'd like to insert this 'uName' variable into mysql. I knew it wouldnt work, but I gave it a shot, and tried to do it with the following query:
statement.executeUpdate("INSERT INTO users(username) VALUES(uName)");
(Where username is the name of the column.)
It didnt work :) Any suggestions?

Assuming you are opening connection to your database in the right way, you can do something like:
String connString = "jdbc:mysql://localhost:3306/<db_name>?user=<user>&password=<password>";
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection(connString);
// open connection
// ...
try
{
String query = "INSERT INTO users (username) VALUES (" + uName + ")"
statement = connect.createStatement();
statement.executeUpdate(query);
}
catch (SQLException se)
{
es.printStackTrace();
}

Related

Embedded SQL INSERT Using Dialog Boxes

I'm currently trying to insert new data into an existing table in my database using embedded SQL. I need to be able to enter my data in a dialog box and then have it shown back to me in a dialog box after it has executed.
My problem seems to be with the "s.executeUpdate(input);" for it tells me that I have an error in MySQL syntax. I'm not really sure how to fix it, or how to change the syntax. Help would be much appreciated!
Connection c = null;
try {
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection("jdbc:mysql://localhost:3306/company - final project", "root", "");
String query = "INSERT INTO works_on (ESSN, PNO, HOURS)" + "Values (?, ?, ?)";
Statement s = c.prepareStatement(query);
String input = JOptionPane.showInputDialog(null, "Info to be Inserted: ");
s.executeUpdate(input);
JOptionPane.showMessageDialog(null, "Data Inserted: " + input);
c.close();
}
catch (Exception e)
{
e.printStackTrace();
}
You're prepared statement requires 3 parameters, but you did not add any. need to call s.addXXX in the proper order to specify the 3 values to insert, wheres "XXX" is the appropriate type for the values

SQL WHERE LIKE clause in JSF managed bean

Hi i have this managed bean where it makes MySQL queries, the problem here is the SQL statement makes a '=' condition instead of 'LIKE'
Here is the code in my managed bean.
Connection con = ds.getConnection();
try{
if (con == null) {
throw new SQLException("Can't get database connection");
}
}
finally {
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM Clients WHERE Machine LIKE '53'");
//get customer data from database
ResultSet result = ps.executeQuery();
con.close();
List list;
list = new ArrayList();
while (result.next()) {
Customer cust = new Customer();
cust.setMachine(result.getLong("Machine"));
cust.setCompany(result.getString("Company"));
cust.setContact(result.getString("Contact"));
cust.setPhone(result.getLong("Phone"));
cust.setEmail(result.getString("Email"));
//store all data into a List
list.add(cust);
}
return list;
Here the SELECT command does not pull all the numbers in 'Machine' column which is like 53, but if i enter a whole value, such as the complete number (53544) in place of 53 then the result is pulled up. I am confused !!
Also if i replace the above select statement with SELECT * FROM Clients the entire database is stored in list. Any ideas ?
Use wildcards:
Like '%53%'
...means everything that contains '53'.
Like '%53' - it ends with 53
LIKE '53%' - it starts with 53
You can also use _ if You want to replace a single character.
You can find a descriptipn HERE
You sql query should be
"SELECT * FROM Clients WHERE Machine LIKE '%53%'

Issue in setting password for existing in JDBC MS Access Workgroup (MDW) Java

Here is my Scenario
I have MS Access DB (MDB file), and work group security file. I have credentials which have all the permit (Administrator user). This DB and MDW file is created on some other computer and i am using it on my computer now.
What I am able to do till now is, I can log in the DB with different user name and password which are existing in the DB. Verified this by using Correct user name and wrong password It give error, but correct credentials it logins.
Now I need to create a interface In Java to basic functionality.
1. Change password of currently logged user.
Change password of current user
Following is my code to change the password
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:"+"mdbTEST";
// mdbTEST is created in System DNS which uses SECURED.MDW file and
// ExtendedAnsiSQL is set to 1
conn = DriverManager.getConnection(database, "administrator", "hello");
String q = "ALTER USER "+uname+" PASSWORD "+newPass+" '"+oldPass+"'";
stmt = conn.createStatement();
stmt.execute(q);
It returns successful.
But when I try to log in the with the username and new password it says wrong passowrd and even the old password stops working.
Moreover, I tried to read all the username and passwords in the WorkGroup file using some third party software, it shows the new password is updated correctly in the MDW file.
I am using JDK 1.7 on Windows XP 32 bit.
What can be the problem? Am I doing something wrong here?
Thanks in Advance.
If you want to put quotes around the password values to accommodate passwords that contain spaces, you should enclose them in double quotes ("). If you enclose them in single quotes (') then the single quote characters become part of the password. For example, after executing my test code...
import java.sql.*;
public class ulsTest {
public static void main( String args[] )
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection(
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};" +
"DBQ=C:\\Users\\Public\\uls\\ulsTest.mdb;" +
"SystemDB=C:\\Users\\Public\\uls\\Security.mdw;" +
"Uid=Gord;" +
"Pwd=obfuscated;" +
"ExtendedAnsiSQL=1;");
String UID = "Tim";
String oldPWD = "oldpassword";
String newPWD = "I like Java";
Statement s = conn.createStatement();
s.execute("ALTER USER " + UID + " PASSWORD \"" + newPWD + "\" \"" + oldPWD + "\"");
// ALTER USER Tim PASSWORD "I like Java" "oldpassword"
System.out.println("User updated.");
s.close();
conn.close();
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
...Tim is able to log in using the new password
I like Java
However, if I change my code to...
s.execute("ALTER USER " + UID + " PASSWORD '" + newPWD + "' '" + oldPWD + "'");
// ALTER USER Tim PASSWORD 'I like Java' 'oldpassword'
...then the single quotes become part of the new password and Tim must type the password...
'I like Java'
...(including the single quotes) to log in.
Side note: I was hoping that a parameterized query might avoid messing with string quoting, but unfortunately the code...
PreparedStatement s = conn.prepareStatement("ALTER USER ? PASSWORD ? ?");
s.setString(1, UID);
s.setString(2, newPWD);
s.setString(3, oldPWD);
s.execute();
...fails with the error:
[Microsoft][ODBC Microsoft Access Driver] Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.

SQL Syntax Problems

Im trying to do this:
String insertQuery=" DELETE FROM Accounts WHERE Username= " + Username + ";";
But im getting this error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'sam' in 'where clause'
Its getting the right username etc I know this by testing, I assume the syntax is wrong but im getting no syntax errors?
The table is called Accounts. The coloums are Username & Password,
You are missing single quotes. In your case(it's string) variable need to be wrapped in them or it'll be interpreted as column.
String insertQuery = "DELETE FROM Accounts WHERE Username = '" + Username + "'";
Recommendation:
Hence i recommend you to use placeholders to avoid this kind of problem. Don't forget to care about a security(SQL Injection for instance). It's worth to say that parametrized statements are also more human-readable, safer and faster as well.
I don't like "hardcoded" queries. Let's imagine a scenario if you had a table with ten columns and imagine how you query will look in this case: absolutely human-unreadable.
An usage of parametrized statements is always very efficient and comfortable practise. Your code looks good and becomes human-readable and what is "main" solution is much more safer and cleaner.
Have look at PreparedStatements. Basic example:
private final String deleteQuery = "DELETE FROM Accounts WHERE Username = ?";
public boolean deleteObject(String username) {
Connection c = null;
PreparedStatement ps = null;
try {
c = DataSource.getConnection();
ps = c.prepareStatement(deleteQuery);
ps.setString(1, username); // numbering starts with 1 not 0!
return ps.executeUpdate() > 0;
}
catch (SQLException ex) {
System.out.println("Error in deleteObject() method: " + ex.getMessage());
return false;
}
finally {
if (c != null) {
try {
c.close();
}
catch (SQLException ex) {
System.out.println("Error in closing conn: " + ex.getMessage());
}
}
}
}
If username is a varchar you need to add single quotes around the value in the where clause.
String insertQuery=" DELETE FROM Accounts WHERE Username= '" + Username + "';";
Since the value is not quoted its identifying the username, I'm assuming its Sam as a column.

How can I display data into my Jtextarea from my data base Mysql

I have problem when I try to display data(the result of a query) from my database mysql to my jTextarea, when I compile I have an error exception like:
SQL Exception: java.sql.SQLException: Can not issue SELECT via executeUpdate()
I have used a "select" query from my table where the name is the name written in my jTextFieldNom,this is my code, I hope that some one help me because I don't know how to resolve the problem, I 'm sure that my query is correct but I don't know where is the problem.
String pilote = "com.mysql.jdbc.Driver";
jComboBoxType.addItemListener(new ItemState());
jComboBoxMenaces.addItemListener(new ItemState());
try {
Class.forName(pilote);
Connection connexion = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root"," ");
Statement instruction = connexion.createStatement();
String a=jTextFieldNom.getText();
String SQL = "select description from table where nomcol="+a+";";
ResultSet rs = instruction.executeQuery(SQL);
instruction = connexion.createStatement();
int rowsEffected = instruction.executeUpdate(SQL);
jTextArea1.append(rs.getString("description"));
}
...... //bloc catch
This line is executing a Select statement which is throwing the error.
int rowsEffected = instruction.executeUpdate(SQL);
You don't need this line because you aren't updating your database.
Also change the append to setText
jTextArea1.setText(rs.getString("description"));
Try this:
String pilote = "com.mysql.jdbc.Driver";
jComboBoxType.addItemListener(new ItemState());
jComboBoxMenaces.addItemListener(new ItemState());
try {
Class.forName(pilote);
Connection connexion = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test","root"," ");
Statement instruction = connexion.createStatement();
String a=jTextFieldNom.getText();
String SQL = "select description from table where nomcol="+a+";";
ResultSet rs = instruction.executeQuery(SQL);
jTextArea1.setText(rs.getString("description"));
}