I'm using Eclipse EE, Tomcat 6 server connected to MySQL server on win7.
I was able to connect to a database through JSP and send commands like SELECT and DESCRIBE but if I try to create a table the JSP code will simply not run!
Why is that?
(Checked my SQL codes on the MySQL command line and it worked. )
JSP error:
org.apache.jasper.JasperException: An exception occurred processing JSP page /index.jsp at
JSP Coding:
try // DB login
{
String connectionURL = "jdbc:mysql://localhost/ofir";
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(connectionURL, "root", "");
stmt = con.createStatement();
connected = true;
}
catch(Exception ex)
{
out.println("Unable to connect to database.");
connected = false;
}
rs = stmt.executeQuery("CREATE table users (fname varchar(50), nname varchar(20), pass varchar(50), email varchar(50), gender boolean, age int(3), region varchar(10), notes varchar(1000))"); // Line of the error
*To be noted about the code- all variables are declared globally using ' <%! '
For CREATE TABLE, we have to use stmt.executeUpdate(sql) . Not stmt.executeQuery(sql)
Related
I have some MySQL scripts that are needed for recreating a database. They work fine when I execute them on the command line using the mysql command.
Now I wrote a Java class that should execute these scripts using a JDBC connection to the MySQL database.
One line in a "create table"-statement in the script is:
registration_date DATETIME DEFAULT CURRENT_TIMESTAMP
This line however won't be executed using the JDBC-MySQL connection. I get the error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Invalid default value for 'registration_date'
The relevant method is shown below. sqlScriptPathpoints to the folder containing the sql scripts. The connectionString has this content: "jdbc:mysql://localhost:3306/testDb?useUnicode=yes&characterEncoding=UTF-8&allowMultiQueries=true"
public static void recreate(String connectionString, String dbUser, String dbPass, String sqlScriptPath) throws Exception {
// Find and filter sql scripts
File file = new File(sqlScriptPath);
File[] scripts = file.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return file.getName().endsWith(".sql");
}
});
List<File> scriptsList = Arrays.asList(scripts);
Collections.sort(scriptsList);
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(connectionString, dbUser, dbPass);
// Load each script and apply it
for (File f : scriptsList) {
System.out.println("Importing script: " + f);
List<String> lines = Files.readAllLines(Paths.get(f.getAbsolutePath()), Charset.forName("UTF-8"));
StringBuilder sb = new StringBuilder();
for (String line : lines) sb.append(line).append("\n");
String sqlStatement = sb.toString();
System.out.print(sqlStatement);
Statement st = conn.createStatement();
st.execute(sqlStatement);
st.close();
}
}
And the relevant part of the script:
CREATE TABLE user
(
id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
username VARCHAR(255),
password VARCHAR(255),
age_group INT,
registration_date DATETIME DEFAULT CURRENT_TIMESTAMP
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
What is the problem here?
I inherited a Java test harness for a MySQL database that was failing with this error on a datetime column defined as NOT NULL with no default defined. I added DEFAULT NOW() and it worked fine after that.
Below is simple Login system. At the moment it will allow me to enter a blank username and password, into the table even though each index is specified as being NOT NULL? It wont allow me to enter duplicates which is what I wanted but how do I catch blank parameters from being entered? What am I missing?
Registration Servlet
....
LoginService loginService = new LoginService();
connection = loginService.getConnection(connection);
loginService.addNewUser(preparedStatement, connection, newUserId, newUserPassword, newUserFirstName, newUserLastName);
...
LoginService method addNewUser
public void addNewUser(PreparedStatement ps, Connection connection, String newUserId, String newUserPassword,String newUserFirstName,String newUserLastname) throws SQLException
{
ps = connection.prepareStatement("INSERT INTO users (userId ,password , userFirstName, userLastName)VALUES(?,?,?,?)");
ps.setString(1, newUserId);
ps.setString(2, newUserPassword);
ps.setString(3, newUserFirstName);
ps.setString(4, newUserLastname);
ps.executeUpdate();
}
To get around of your current issue, you can add this to the beginning of addNewUser method (before the line: ps = connection.prepareStatement("...");)
if (newUserId != null && "".equals(newUserId.trim()))
newUserId = null;
if (newUserPassword != null && "".equals(newUserPassword.trim()))
newUserPassword = null;
You should pass real NULL value in the JDBC parameters (empty strings are not good enough)
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'.
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"));
}
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();
}