So for example if I have an array list of strings, how do I put them into a database sequentially.
For example if my array list is: "john", "sally", "rob"
How can I come put that into my database such that row 1 is john, row 2 is sally, row 3 is rob.
I was thinking something along the lines of:
for(int i = 0; i < array.size(); i++){
query = "insert into database values(i);
}
But I am not sure if that is the correct approach because I will also be inserting other values into the database other than the array.
I assume you mean a simple insertion;
First you have the database connection, Like this:
public class DBConnection {
final private String url = "jdbc:mysql://localhost/";
final private String databaseName = "test";
final private String user = "root";
final private String password = "159753";
public Connection Connect() {
Connection c = null;
try {
c = DriverManager.getConnection(url + databaseName, user, password);
} catch (SQLException ex) {
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
}
return c;
}}
Below is a simple example of insertion:
public static void main(String[] args) {
Connection con = new DBConnection().Connect();
String sql = "INSERT INTO nameTable (name) values (?)";
PreparedStatement stmt;
try {
stmt = con.prepareStatement(sql);
List<String> names = new ArrayList();
names.add("John");
names.add("Sally");
names.add("Rob");
for (String name : names) {
stmt.setString(1, name);
stmt.execute();
}
stmt.close();
con.close();
} catch (SQLException ex) {
System.err.println("Error = " + ex);
}
}}
PS: But you can use a Java Persistence API too. The wikibook is a good resource to use as reference
Related
I am trying to check if a specific row exists in a table that includes two given parameters: record_id and modifiedDate. So far my code does not work.
public void doSomething(int RECORD_ID) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String modifiedDate = dateFormat.format(date);
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "user", "pass");
Statement stmt = connection.createStatement();
String checkIfInDB = "select exists(select * from table where reference = ${RECORD_ID} and creation_date = '${modifiedDate}');"
ResultSet rs = stmt.executeQuery(checkIfInDB);
if(rs.next()) {
println "Query in db"
stmt.close();
connection.close();
return;
}
else {
String command = "INSERT INTO table(reference, creation_date) VALUES (${RECORD_ID}, '${modifiedDate}');"
stmt.executeUpdate(command)
println "Success"
stmt.close();
connection.close();
return;
}
}
If the user inserts a RECORD_ID and date that already exists, the program adds it to the table anyway, when it should print 'Query in db'.
I would appreciate any help to solve this issue.
Rather than listing what was wrong with the provided code I offer an example of a working example that could be used to help you along your journey...
public static void main(String[] args) {
int recordId = 1;
String jdbcSource = "jdbc:mysql://localhost:####/";
String user = "****";
String password = "****";
String checkIfInDB = "select count(*) as cnt from example_schema.example_table where example_table.reference = ? and example_table.creation_date = ?";
try (Connection connection = DriverManager.getConnection(jdbcSource, user, password)) {
PreparedStatement stmt = connection.prepareStatement(checkIfInDB);
stmt.setInt(1, recordId);
stmt.setDate(2, java.sql.Date.valueOf(LocalDate.now()));
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
System.out.println("at least one row matched");
return;
} else {
// to-do implement insert statement
return;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
I have following program which insert emoji and any text to my MySql AWS Database. I was unable to add Emojis in my MySql database, but then i fixed this problem by changing collation and adding this-> SET NAMES utf8mb4; query before my previous insert query but now i am unable to get last inserted id from it. what should i do in order to insert emoji as well as to get last inserted id from it.
Here is my code.
public static JSONObject emoji(String comment) {
JSONObject json = new JSONObject();
Connection con = null;
PreparedStatement stmt = null;
String newInsertId = "";
try {
BasicDataSource bds = DBConnection.getInstance().getBds();
con = bds.getConnection();
String query = "SET NAMES utf8mb4; insert into emojis set message = '" + comment + "';";
stmt = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
if (stmt.executeUpdate() > 0) {
json.put("success", 1);
}
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()) {
newInsertId = rs.getString(1); //giving empty values cause of that SET NAMES utf8mb4; query
}
System.out.println(newInsertId); //empty
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
DbUtils.close(con);
DbUtils.close(stmt);
} catch (Exception e) {
e.printStackTrace();
}
}
return json;
}
static int create() throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 2.建立连接
conn = JdbcUtils.getConnection();
// conn = JdbcUtilsSing.getInstance().getConnection();
// 3.创建语句
String sql = "insert into user(name,birthday, money) values ('name2 gk', '1987-01-01', 400) ";
ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);//参数2最好写上,虽然Mysql不写也能获取但是不代表别的数据库可以做到
ps.executeUpdate();
rs = ps.getGeneratedKeys();
int id = 0;
if (rs.next())
id = rs.getInt(1);
return id;
} finally {
JdbcUtils.free(rs, ps, conn);
}
}
——————————————————————————————————————————————————————
Focus on this 'Statement.RETURN_GENERATED_KEYS'
I would like to create a method that returns an array with all the values from the database.
This is what I have so far:
package ch.test.zt;
import java.sql.*;
class Database {
static boolean getData(String sql) {
// Ensure we have mariadb Driver in classpath
try {
Class.forName("org.mariadb.jdbc.Driver");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
String url = "jdbc:mariadb://localhost:3306/zt_productions?user=root&password=test";
try {
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
return rs.next();
}
catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
That means, I could use Database.getData("SELECT * FROM users") and I get an array with all the data from the database that I need.
In my code above I am using return rs.next();, which is definitely wrong. That returns true.
rs.next(); just tell whether your result set has data in it or not i.e true or false , in order to use or create array of the actual data , you have to iterate over your result set and create a user object from it and have to add that object in your users list
Also change the signature
static List<User> getData(String sql)
And best to use like Select Username,UserId from Users; as your sql
something like this:
try { List<User> userList = new ArrayLisy();
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
//until there are results in the resultset loop over it
while (rs.next()) {
User user = new User();
user.SetName(rs.getString("username"));
// so on.. for other fields like userID ,age , gender ,loginDate,isActive etc ..
userList.add(user);
}
}
when you don't know about the columns of the table you are going to fetch then you can find the same using :
Now you know all the information then you can construct a proper query using it
and work from this
DatabaseMetaData metadata = connection.getMetaData();
ResultSet resultSet = metadata.getColumns(null, null, "users", null);
while (resultSet.next()) {
String name = resultSet.getString("COLUMN_NAME");
String type = resultSet.getString("TYPE_NAME");
int size = resultSet.getInt("COLUMN_SIZE");
System.out.println("Column name: [" + name + "]; type: [" + type + "]; size: [" + size + "]");
}
}
String [] tableTypes = { "TABLE" };
DatabaseMetaData md = (DatabaseMetaData) dbConnection.getMetaData();
ResultSet rs = md.getTables(null, null, "%", tableTypes);
while (rs.next()) {
System.out.println(rs.getString(3));
}
Im using this part of the code to get all tables from my local oracle database but I need to change it in order to get back only the tablet that have only one primary key. Any ideas?
You could use DatabaseMetaData.getPrimaryKeys() for each table in that loop:
String [] tableTypes = { "TABLE" };
DatabaseMetaData md = dbConnection.getMetaData(); // the cast is unnecessary!
ResultSet rs = md.getTables(null, null, "%", tableTypes);
while (rs.next())
{
String schema = rs.getString(2);
String table = rs.getString(3);
ResultSet pkRs = md.getPrimaryKeys(null, schema, table);
int colCount = 0;
while (pkRs.next())
{
colCount ++;
}
pkRs.close();
if (colCount = 1)
{
System.out.println("Table " + table + " has a single column primary key");
}
}
However, this will be awfully slow. Using a query that retrieves this information directly from user_constraints and user_cons_columns is going to be a lot faster:
select col.table_name, count(*)
from user_constraints uc
join user_cons_columns col
on col.table_name = uc.table_name
and col.constraint_name = uc.constraint_name
where constraint_type = 'P'
group by col.table_name
having count(*) = 1;
You can use this code :
static Statement statement = null;
static ResultSet result = null;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try {
Class.forName(driverClassName);
dbConnection = DriverManager.getConnection(url, username, passwd);
statement = dbConnection.createStatement();
String[] tableTypes = {"TABLE"};
DatabaseMetaData dbmd;
dbmd = dbConnection.getMetaData();
result = dbmd.getTables("%", username, "%", new String[]{tableTypes[0]});
while (result.next()) {
String tableName = result.getString("TABLE_NAME");
ResultSet tempSet = dbmd.getPrimaryKeys(null, username, tableName);
String keyName="";
int counter=0;
while (tempSet.next()) {
keyName = tempSet.getString("COLUMN_NAME");
counter++;
}
if(counter == 1) {
System.out.println(tableName);
}
}
} catch (Exception e) {
}
}
Table can have up to one primary key. This primary can be compound - i.e. consisting of multiple columns. The other (2nd) key might be UNIQUE (+ not NULL) which is not exactly the same as primary.
Best way how to check columns is to query ALL_CONTRAINTS view. JDBC method DatabaseMetaData has only limited functionality.
The aim of the code here is to Read a record by selecting a column.
I have following columns in the SQL DB.
------------------------------
|id | Topic | Comment | Time |
------------------------------
What I want to do is:-
Read the DB
Able to select rows by Topic
Show or Return the values of selected rows by Topic
The Topic could be duplicated, however the duplicated values should not been seen during the process of selection but the values of all column should be retrieved (as well as duplicated ones).
public class ReadRecordTopic{
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/STUDENTS?user=root&password=";
// Database credentials
//static final String USER = "username";
//static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating statement..." + "\n");
stmt = conn.createStatement();
String sql = "SELECT id, Topic, Comment, Time FROM Registration";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
String Topic = (String) rs.getString("Topic");
String Comment = rs.getString("Comment");
String Time = rs.getString("Time");
String menu [] = Topic.split(",");
Object[] selectionValues = menu;
String initialSelection = "";
Object selection = JOptionPane.showInputDialog(null,
"Please select the Topic.", "Reseach Forum Menu",
JOptionPane.QUESTION_MESSAGE, null, selectionValues,
initialSelection);
String a = "Research Topic: " + Topic + "\n";
String b = "[" + Time + "]" + " Comment:" + Comment + "\n";
if(selection == Topic){JOptionPane.showMessageDialog(null, a + b);
}
}
rs.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
1- Create Registration.class
public class Registration{
private int id;
private String topic;
...
...
...
//getters and setters
}
2- Change your sql and function name for what do yo want and use it.
//for order topic
String sql = SELECT id, Topic, Comment, Time FROM Registration order by topic.
//function for just spesific topic
public class ArrayList<Registration> getRegisWithTopic(String topicName){
String sql = SELECT id, Topic, Comment, Time FROM Registration order by topic WHERE TOpic = topicName ;
}
3- in while create new Registration.class and add to ArrayList and return this list
ArrayList<Registration> newList = new ArrayList<Registration>();
while(rs.next()){
Registration newReg = new Registration();
//Retrieve by column name
newReg.setId(rs.getInt("id"));
newReg.setTopic(rs.getString("Topic"));
...
...
...
//add this obj to list
newList.add(newReg);
}
return newList ;