A Java MySQL INSERT(using PreparedStatement) - java

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

Related

how to fetch data hierarchal data from database in java

there is table of employee in database like in this image and use jdbc and java to fetch data from table. expected result also in image.
desired output in image
You can create an Employee class which contains the list of reports as below along with empId and reportingId:
public class Employee {
private String empId;
private String reportingId;
private List<Employee> reports;
public Employee(String empId, String reportingId) {
this.empId = empId;
this.reportingId = reportingId;
this.reports = new ArrayList<>();
}
public String getEmpId() {
return empId;
}
public String getReportingId() {
return reportingId;
}
public List<Employee> getReports() {
return reports;
}
}
// Step 1: Connect to the database
Connection conn = DriverManager.getConnection(connectionString, username, password);
// Step 2: Execute a SELECT statement
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT empId, reportingId FROM employee");
// Step 3: Iterate over the resultset and create a Map of Employee objects
Map<String, Employee> employees = new HashMap<>();
while (rs.next()) {
String empId = rs.getString("empId");
String reportingId = rs.getString("reportingId");
Employee employee = new Employee(empId, reportingId);
employees.put(empId, employee);
}
// Step 4: Iterate over the Map and create the hierarchy of Employee objects
for (Employee employee : employees.values()) {
Employee manager = employees.get(employee.getReportingId());
if (manager != null) {
manager.getReports().add(employee);
}
}
// The hierarchy of Employee objects is now complete
You can then print the hierarchy of Employee objects using a recursive method, like this:
public void printHierarchy(Employee employee, int level) {
for (int i = 0; i < level; i++) {
System.out.print("\t");
}
System.out.println(employee.getEmpId());
for (Employee report : employee.getReports()) {
printHierarchy(report, level + 1);
}
}
Call the printHierarchy method from 101 employee
Output:
101
1013
1012
101222
101223
1011
101101
101102

Spring boot MySQL request return null when it shouldn't

I'm making a rest API for an App I'm creating,
I have a MySQL database and I'm using Springboot.
I coded this
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MySQLInfosGateway implements InfosGateway {
private NamedParameterJdbcTemplate jdbcTemplate;
public MySQLInfosGateway(NamedParameterJdbcTemplate jdbcTemplate){
this.jdbcTemplate=jdbcTemplate;
}
#Override
public Personne getInfos(String badge){
var query = "select NOM, PRENOM from PERSONNEL where BADGE = "+badge;
var result = jdbcTemplate.query(query, new ResultSetExtractor<Object>() {
#Override
public Object extractData(ResultSet resultSet) throws SQLException, DataAccessException {
resultSet.next();
return new Personne(resultSet.getString("NOM"),resultSet.getString("PRENOM"));
}
});
return (Personne) result;
}
}
Here's my Personneclass :
package com.piroux.phoenixrhbackend.domain.entities;
public class Personne {
private String nom;
private String prenom;
public Personne(String nom, String prenom){
this.nom=nom;
this.prenom=prenom;
}
public String getPrenom() {
return prenom;
}
public String getNom() {
return nom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public void setNom(String nom) {
this.nom = nom;
}
}
and I'm trying with the following request on Postman:
localhost:8080/fonction-recup-infos/nom-prenom?badge=50387
If I execute the request select NOM, PRENOM from PERSONNEL where BADGE = 50387
In a SQL script => I get the correct NOM and PRENOM;
With my API => I get null and null
For you to know, BADGE is a unique String, so there's only one NOM and PRENOM for each BADGE.
It's my first time creating a REST API so if any information is missing please tell me
A couple of things wrong with your code. First never use concatenation to create a query string based on user input. It is dangerous. Second I would suggest using the RowMapper instead of the ResultSetExtractor it is easier to use.
You are using getString("<column-name>") if your database doesn't expose the metadata this won't work and you have to use positional identifiers.
All in all I suggest you do this.
#Override
public Personne getInfos(String badge){
var query = "select NOM, PRENOM from PERSONNEL where BADGE = :badge";
var result = jdbcTemplate.queryForObject(query, Map.of("badge", badge), (rs, rowNum) ->
new Personne(rs.getString("NOM"), rs.getString("PRENOM"));
return result;
}
NOTE: You also might want to try nom and prenom as the column names, yuo are using MySQL which can be a bit picky about casing (depending on your configuration of MySQL and the platform you are running on).
Change this line from
var query = "select NOM, PRENOM from PERSONNEL where BADGE = "+badge;
to
var query = "select NOM, PRENOM from PERSONNEL where BADGE = '" + badge + "'";
It might be resolved.

Error while inserting in sql2o

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.

removing duplicate records in list

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.

Filling a combo box with mysql data

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);

Categories