Skip to content

Instantly share code, notes, and snippets.

@theArjun
Created February 14, 2019 07:17
Show Gist options
  • Select an option

  • Save theArjun/ea7c641ce649668153266e3973b4ff53 to your computer and use it in GitHub Desktop.

Select an option

Save theArjun/ea7c641ce649668153266e3973b4ff53 to your computer and use it in GitHub Desktop.
INSERT Query using String Format in JDBC
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.SQLException;
public class StringFormat {
public static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
public static final String JDB_URL = "jdbc:mysql://localhost:3306/gces";
public static void main(String[] args) {
String insertQuery;
String name = "Hari KC", address = "Lamachaur";
float salary = 2345364;
try {
insertQuery = String.format("INSERT INTO `employees` ( `username`, `address`, `salary`) VALUES ('%s', '%s', '%f')", name,address, salary);
Class.forName(JDBC_DRIVER);
Connection conn = DriverManager.getConnection(JDB_URL,"root","");
Statement st = conn.createStatement();
st.executeUpdate(insertQuery);
st.close();
}
catch(SQLException exc) {
exc.printStackTrace();
}
catch(ClassNotFoundException exc) {
exc.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment