I have these codes
DBCollection.java
public LogInHandler userGreetName()
{
LogInHandler login = new LogInHandler();
String query = null;
try
{
query = "SELECT First_Name FROM user_information WHERE Username = '"+login.getUsername()+"'";
rs = stmt.executeQuery(query);
rs.next();
login.setGreetName(rs.getString("First_Name"));
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e.toString());
}
return login;
}
On my mainWindow.java I have formWindowOpened event and contains the codes
DBCollection dbc = new DBCollection();
greetNameL.setText(dbc.userGreetName().getGreetName());
LogInHandler.java
public class LogInHandler extends ValidateLogin{
DBCollection dbc = new DBCollection();
private String username;
private String greetName;
public void setGreetName(String temp)
{
greetName = temp;
}
public String getGreetName()
{
return greetName;
}
public void setUsername(String temp)
{
username = temp;
}
public String getUsername()
{
return username;
}
I have login.setUsername(usernameTF.getText()); in my loginWindowGUI
here's my problem.. I cant retrieve the First_Name column in my database.. it displays null. and is my WHERE condition in query is correct? help please..
Firstly, the way you've set your code exposes you to SQL injection.
query = "SELECT First_Name FROM user_information WHERE Username = '"+login.getUsername()+"'";
rs = stmt.executeQuery(query);
rs.next();
login.setGreetName(rs.getString("First_Name"));
Something like the below should do the same job as your code, but protect you from SQL injection.
query = "SELECT First_Name FROM user_information WHERE Username = ?";
PreparedStatement preparedStatement = dbConnection.prepareStatement(query);
preparedStatement.setString(1, login.getUsername());
ResultSet rs = preparedStatement.executeQuery(query);
rs.next();
login.setGreetName(rs.getString("First_Name"));
I don't think that is what's causing your code not to work however. You need to give us more information.
Have you tried directly querying the DB with the following string?
SELECT First_Name FROM user_information WHERE Username = 'A user name that is definitely in the DB';
That should verify if your query is correct or not. If it works, then I would go into debug mode in Netbeans. Put a breakpoint before the following line
rs = stmt.executeQuery(query);
Check to see if login.username variable is populated. If that field is null, then your problem is there.
Related
I want to create table and insert some values into it. I'm trying to do it using H2 database and sql2o framework at the code below:
public class Main {
private static final String DB_DRIVER = "org.h2.Driver";
private static final String DB_CONNECTION = "jdbc:h2:~/test";
private static final String DB_USER = "";
private static final String DB_PASSWORD = "";
static String TABLE = "PERSONS";
static Sql2o sql2o;
public static void main(String[] args) throws Exception, SQLException {
sql2o = new Sql2o(DB_CONNECTION, DB_USER, DB_PASSWORD);
createTable();
insertIntoTable();
}
public static void createTable() {
final String tableSql = "CREATE TABLE IF NOT EXISTS " + TABLE + " (id int, name varchar(255))";
try (org.sql2o.Connection con = sql2o.beginTransaction()) {
con.createQuery(tableSql).executeUpdate();
con.commit();
con.close();
}
}
public static void insertIntoTable() {
String insertSql = "insert into " + TABLE + " values (:id, :name)";
try (org.sql2o.Connection con = sql2o.open()) {
con.createQuery(insertSql).addParameter("id", 1).addParameter("name", "test").executeUpdate();
con.close();
}
}
}
And after all I get an error:
Error preparing statement - Column count does not match; SQL
statement: insert into PERSONS values (?, ?) [21002-191]
The SQL statement is correct, the names and types of columns match each other, and I really can't understand what the problem.
There was an existing PERSONS table that did not match the structure in the CREATE TABLE IF NOT EXISTS statement. Dropping and recreating the table solved the problem.
I have a small question to you guys.
I tryed to add user to database.
User have field like: id, name, surname etc.
Method
public static String insertUsertoDatabase(Connection con, User userToAdd)
doing something like this
// the mysql insert statement
String query = " insert into User (id,log,pass)"
+ " values (?, ?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setInt(1, 1);
preparedStmt.setString(2, "h");
preparedStmt.setString(3, "l");
setUser method
public String setUser(User userToBase) {
return insertUsertoDatabase(con, userToBase);
}
and main.java
User us1 = new User("9", "h", "l");
db.setUser(us1); //insert to database User u1
How can I put values from User constructor to preparedStmt ?
I have a constructor like that:
public class User(id, login, pass) {
this.id = id;
etc.
}
but i want to know how can I send data from constructor
User us1 = new User("9", "h", "l");
to my method
public static String insertUsertoDatabase(Connection con, User userToAdd)
preparedStmt.setInt(1, 9); <------------- from User constructor
preparedStmt.setString(2, "h");
preparedStmt.setString(3, "l");
You probably need something like that:
// TODO: use meaningful names
private String pim;
private String pam;
private String poom;
public User(String pim, String pam, String poom) {
this.pim = pim;
this.pam = pam;
this.poom = poom;
}
public String getPim() {
return this.pim;
}
// ...
Then:
User usr1 = new User("9", "h", "l");
usr1.getPim() // = "9"
// ...
Some reading on constructors
Hi I'm developing app for a school project and I want need to create a user which will be saved in the database.
I've created a Profile class
public class Profile{
private String username;
private String password;
public Profile(String _username, String _password){
this.username = _username;
this.password = _password;
}
public void setUsername(String username){
this.username = username;
}
public String getUsername(){
return this.username;
}
public void setPassword(String _password){
this.password = _password;
}
public String getPassword(){
return this.password;
}
Than I have created a DBConnect class which will contain all the methods one of them being CreateProfile which I want to user to Insert the values for new profile into the database "user" table.
public class DBConnect {
private Connection dbConnection;
public DBConnect(){
try{
dbConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?user=root");
}catch(Exception ex){
System.out.println("Connection failed :" +ex);
}
}
public void createProfile(Profile profile){
Statement stm = null;
try{
stm = dbConnection.createStatement();
stm.executeUpdate("INSERT INTO User (Username,Password) VALUES (\"" + profile.getUsername() + "\", \"" + profile.getPassword()+ "\"");
}catch(SQLException ex){
System.out.println(ex);
}
}
Finally in my JFrame I have two textFeilds username and password which I want to use in order to pass on the parameters for profile constructor. Once this is done I DBConnect object to start of the connection and than I'm calling the Create Profile method which is declared in the DBConnect.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Profile p = new Profile(jTextField1.getText(), jPasswordField1.getText());
DBConnect dbc = new DBConnect();
dbc.createProfile(p);
Everything compiles but when I run the program and try to create a new Profile I get this Error.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
My MySQL tables is a simple table with two columns called 'Username' and 'Password'
You need to put the right parenthesis inside the string:
stm.executeUpdate("INSERT INTO User (Username,Password) VALUES (\"" + profile.getUsername() + "\", \"" + profile.getPassword()+ "\")";
Hi while developing one of my web application i am storing the user information in to an ArrayList based on sql query executed, it contain duplicate objects how to remove duplicate objects in list , i already tried some method but it still not working.
This Is My Code Correct me where i am wrong
public ArrayList loadData() throws ClassNotFoundException, SQLException {
ArrayList userList = new ArrayList();
String url = "";
String dbName = "";
String userName = "";
String password = "";
Connection con = null;
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection(url + dbName, userName, password);
PreparedStatement ps = null;
try {
String name;
String fatherName;
int Id;
String filePath;
int age;
String address;
String query = "SELECT NAME,FATHERNAME,AGE,ADDRESS,ID,FILEPATH FROM USER_INFORMATION ,USER_PHOTO WHERE ID=USER_ID";
ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
name = rs.getString(1);
fatherName = rs.getString(2);
age = rs.getInt(3);
address = rs.getString(4);
Id = rs.getInt(5);
filePath=rs.getString(6);
/* if(flag)
{
prev=Id;
flag=false;
}
else if(Id==prev)
{
TEMP=TEMP+";"+filePath;
}*/
//PhotoList = PhotoList(Id, con);
UserData list = new UserData();
list.setName(name);
list.setFatherName(fatherName);
list.setAge(age);
list.setAddress(address);
list.setId(Id);
// list.setFilePath(filePath);
userList.add(list);
}
ps.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
ArrayList al = new ArrayList();
HashSet hs = new HashSet();
hs.addAll(userList);
al.clear();
al.addAll(hs);
return al;
}
And My Bean Class contant is
public class UserData {
private String name;
private String fatherName;
private int Id;
//private String filePath;
private int age;
private String address;
public UserData()
{
}
public UserData(String name, String fatherName,int Id, int age,String address)
{
this.name = name;
this.fatherName = fatherName;
this.Id = Id;
//this.filePath=filePath;
this.age=age;
this.address=address;
}
//GETTER AND SETTER..
General Idea: Use Set, not List. But you must override hash and equals of the class.
If you want a Collection of objects that does not have a specific order and you don't want duplicates, it's better for you just to use a Set like for example HashSet, or, if in your set the order is important, the TreeSet.
Just remember to override the hash and equals methods.
if you add this to your bean everything should work:
public int hashCode() {
return (name + fatherName+ Id + filePath + age + address).hashCode();
}
public boolean equals(Object obj) {
return ( hashCode() == obj.hashCode() );
}
Your userdata class does not implement equals or hashcode. This means two instances created with the same values will not be counted as duplicates. This is why the set contains duplicates.
For example
UserData u1 = new UserData("Foo", "bar",1, 1,"baz");
UserData u2 = new UserData("Foo", "bar",1, 1,"baz");
u1 and u2 are not considered equal as they are different objects. Adding an equals and hashcode method should fix this. However even better is adarshr's idea of removing dupes in the SQL.
All duplicates must be removed at an SQL level. Your SQL is suggesting that it could be generating duplicate records.
String query = "SELECT NAME,FATHERNAME,AGE,ADDRESS,ID,FILEPATH FROM USER_INFORMATION ,USER_PHOTO WHERE ID=USER_ID";
What does the clause ID = USER_ID mean? Shouldn't you be passing in that value as an input to your query?
Also, is the column ID a primary key? Otherwise, use a where clause that doesn't generate duplicates.
hi everyone i have this code but don't know why it doesn't work!
//in database class
String query = "SELECT group_name FROM customer ORDER BY group_name";
java.sql.PreparedStatement stm = connection.prepareStatement(query);
rs = stm.executeQuery(query);
while (rs.next()) {
String x = rs.getString("group_name");
System.out.println(x);
}
rs.close();
}
//combo box action
int group = jcombobox.getSelectedIndex();
rg_domain rg = new rg_domain();
rg.setGroup(group);
rg.setPhone_number(phone_no);
dbconnection db = new dbconnection();
db.broadcastmsgservice_sms(rg);
}
//domain class
private String group;
public void setGroup(String group) {
this.group = group;
}
public String getGroup() {
return group;
}
can anyone help me please..
Your question is not very clear, but here's how you fill a combo box with results retrieved from the database:
// Create an array list to be filled with group names
ArrayList<String> groupNames = new ArrayList<String>();
String query = "SELECT group_name FROM customer ORDER BY group_name";
PreparedStatement stm = connection.prepareStatement(query);
ResultSet rs = stm.executeQuery(query);
while (rs.next()) {
String groupName = rs.getString("group_name");
// add group names to the array list
groupNames.add(groupName)
}
rs.close();
// Populate the combo box
DefaultComboBoxModel model = new DefaultComboBoxModel(groupNames.toArray());
comboBox.setModel(model);