Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JDBC inserting variables to database

I'm passing my method InsertQuery variables from another method which are entered by the user via Scanner.

How do I fill in the iName, iType etc. into my iQuery so that I can insert them into my DB?

public void InsertQuery (String iName, String iType, int health_Problem, Date date2, String aRemind, String docName, String docType, String docAdress)
{
    final String url = "jdbc:mysql://localhost/ehealthdb?serverTimezone=UTC";
    final String DBUSER = "root";
    final String DBPSWD = "root";
    
    try {
        Connection con = DriverManager.getConnection(url,DBUSER,DBPSWD);
        Statement stmt = con.createStatement();
        
        String iQuery = "INSERT into appointment" 
                        + "(ID, PatientID, Insurance_Name, Insurance_Type, Health_Problem, Appointment_Date, Appointment_Remind, Doctor_Name,Doctor_Type,Doctor_Adress)"
                        + "values ('1','1',,'Gesetzlich','5','15.01.2020','1 Week','Musterarzt','Hausarzt','Musterstraße')";
        
        stmt.executeUpdate(iQuery);
        
    } catch (Exception e) {
        System.out.println("Something went wrong @InsertQuery");
    }
} 
like image 593
P3ngu62 Avatar asked Mar 25 '26 21:03

P3ngu62


1 Answers

The easiest approach would probably be to use a PreparedStatement:

public void insertQuery
     (String iName, String iType, int healthProblem, Date date2, String aRemind, String docName, String docType, String docAddress)
     throws SQLException {

    final String url = "jdbc:mysql://localhost/ehealthdb?serverTimezone=UTC";
    final String DBUSER = "root";
    final String DBPSWD = "root";

    try (Connection con = DriverManager.getConnection(url,DBUSER,DBPSWD);
         PreparedStatement stmt = con.prepareStatement(
                 "INSERT into appointment" +
                         "(ID, PatientID, Insurance_Name, Insurance_Type, Health_Problem, Appointment_Date, Appointment_Remind, Doctor_Name, Doctor_Type, Doctor_Adress) " +
                         "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")) {

        stmt.setString(1, iName);
        stmt.setString(2, iType);
        stmt.setInt(3, healthProblem);
        stmt.setTimestamp(4, new Timestamp(date2.getTime()));
        stmt.setString(5, aRemind);
        stmt.setString(6, docName);
        stmt.setString(7, docType);
        stmt.setString(8, docAddress);

        stmt.executeUpdate();
    }
}
like image 83
Mureinik Avatar answered Mar 29 '26 14:03

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!