This is what i need to create.
I have a web site where the user can come and design an application form according to their need/requirement. Basically there is a HTML designer available in the website to perform this action. The user can drag and drop HTML components which in turn creates an application form in pure HTML. For example, for creating the "Personal Section" the user can drag & drop the label component and TextBox component and put the label text as "FirstName" and so on. I need to have a database created according to the form the one user has created. If he created the personal section with only FirstName and LastName the table created should have only those two cols. (ie, its up to the user to decide on col name at the time of form creation, the SQL queries for inserting and Updating DB fields all should perform dynamically). Please help me to solve this issue. Any suggested pattern there to apply? (The web application is created using Java)
Any help will be appreciated greatly
Thanks
You may need to code for some sort of form builder which builds the form on the fly and can take help from following code to create dynamic sql tables. This is just a hint not the perfect solution for your problem
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest", "root", "123");
Statement st = con.createStatement();
System.out.println("connection has been made ");
Scanner scanner = new Scanner(System.in);
System.out.println("please enter table name ");
String tableName = scanner.next();
String strr = null;
System.out.println("Enter no of columns you like to use: ");
int noc = scanner.nextInt();
for (int i = 1; i <= noc; i++) {
BufferedReader bf = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Enter column name with type ");
String s1 = bf.readLine();
if (strr == null) {
strr = s1;
} else {
strr = strr + s1;
}
}
st.executeUpdate("create table " + tableName + "(" + strr + ")");
System.out.println("your table " + tableName
+ " has been created!!!");
ResultSet rs = st.executeQuery("SELECT * FROM " + tableName);
ResultSetMetaData rsmd = rs.getMetaData();
int NumOfCol = rsmd.getColumnCount();
System.out.println("Number of Columns of your table =" + tableName
+ " " + NumOfCol);
System.out.println("Column names are ");
for (int i = 1; i <= NumOfCol; i++) {
System.out.println(rsmd.getColumnName(i));
}
String strn = null;
System.out.println("please enter values you need to insert");
for (int i = 1; i <= NumOfCol; i++) {
String s5 = scanner.next();
if (strn == null) {
strn = s5;
} else
strn = strn + s5;
}
System.out.println(strn);
st.executeUpdate("insert into " + tableName + " values" + "("
+ strn + ")");
System.out.println("your table " + tableName
+ " has been filled!!!");
con.close();
System.out.println("connection has been colsed ");
}
catch (Exception e) {
System.out.println(e.getMessage());
}
Related
This question already has answers here:
Retrieve column names from java.sql.ResultSet
(14 answers)
Closed 3 years ago.
I have a 3 tables I have joined this query executes and prints out the tables data.
try {
Connection conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
System.out.println("Connected");
Statement st = conn.createStatement();
String query = "SELECT s.*, sup.name as supplierName , p.name as partName "+
"FROM supplies s "+
"INNER JOIN supplier sup on s.supplierNum = sup.supplierNum "+
"INNER JOIN parts p on s.partNum = p.partNum";
ResultSet rs = st.executeQuery(query);
while(rs.next()) {
System.out.println(rs.getString("supplierNum"));
System.out.println(rs.getString("partNum"));
System.out.println(rs.getString("quantity"));
System.out.println(rs.getString("supplierName"));
System.out.println(rs.getString("partName"));
space();
}
} catch(Exception ex) {
System.out.println(ex);
}
But I was trying to add the column names so instead of the console printing:
It would to print the column names cascaded
supplierNum: S1
partNum: P1
quantity: 300
name: Smith
part: Nut
As suggested in https://stackoverflow.com/a/696794/11226302
You need to get the ResultSet meta data to programmatically get your column names from db.
Else, you can manually enter the names as suggested in other answers.
while(rs.next()) {
System.out.println("Supplier Name " + rs.getString("supplierNum"));
System.out.println("Part Name "+rs.getString("partNum"));
System.out.println("Quantity "+ rs.getString("quantity"));
System.out.println("SupplierName "+rs.getString("supplierName"));
System.out.println("PartName "+rs.getString("partName"));
space();
}
You can of course hard-code the column names because you already know them.
If you want to get them programmatically, then use the ResultSetMetaData similar to this:
Connection connection = ...
try (PreparedStatement ps = connection.prepareStatement(QUERY)) {
ResultSet resultSet = ps.executeQuery();
// get the meta data from the result set
ResultSetMetaData rsMeta = resultSet.getMetaData();
// receive the column count
int columnCount = rsMeta.getColumnCount();
// iterate them (their indexes start at 1, I think)
for (int i = 1; i < columnCount + 1; i++) {
// and print the column name, the type and the type name
System.out.println(rsMeta.getColumnName(i)
+ " ("
+ rsMeta.getColumnType(i)
+ ", "
+ rsMeta.getColumnTypeName(i)
+ ")");
}
} catch ...
...
}
If you want to directly output the column in your while loop, then get the meta data before that loop
ResultSetMetaData rsMeta = rs.getMetaData();
and then, inside the loop do
System.out.println(rsMeta.getColumnName(1) + ": " + rs.getString("supplierNum"));
System.out.println(rsMeta.getColumnName(2) + ": " + rs.getString("partNum"));
System.out.println(rsMeta.getColumnName(3) + ": " + rs.getString("quantity"));
System.out.println(rsMeta.getColumnName(4) + ": " + rs.getString("supplierName"));
System.out.println(rsMeta.getColumnName(5) + ": " + rs.getString("partName"));
From a resultSet you can optain his metadata
ResultSetMetaData meta = rs.getMetaData();
int cols = meta.getColumnCount();
for (int i = 1; i <= cols; i++) {
String colName = meta.getColumnName(i);
System.out.printf("%s=%s\n", colName, rs.getString(i);
...
}
I've been trying to solve this issue for the past couple of days. I have a SerachUser function where I input all the data like age, gender, city and interests into each string and check them into a select query command.
If data is present, I print them out.
Unfortunately the search isn't working completely. For eg: my table user doesn't have 'F' gender. But if I type 'F' I still get data instead of displaying "ResultSet in empty in Java".
Below is a brief code I have done.
try{
conn = DriverManager.getConnection(DB_URL,"shankarv5815","1807985");
st = conn.createStatement();
rs = st.executeQuery("Select loginID, f_name, l_name from users where gender = '" +
searchUser.getGender() + "' and age between '" + min + "' and '" + max + "' and city = '" +
searchUser.getCity() + "' and interest1 = '" + searchUser.getInterest1() +
"' or interest2 = '" + searchUser.getInterest1() + "' or interest3 = '" +
searchUser.getInterest1() + "' and loginID != '" + curUser + "'");
if (rs.next() == false) {
System.out.println("ResultSet in empty in Java");
}
else {
do {
String id = rs.getString(1);
String fName = rs.getString(2);
String lName = rs.getString(3);
System.out.print(id +" ," + fName + ", " + lName);
System.out.println();
} while (rs.next());
}
}
catch(SQLException e){
e.printStackTrace();
}
finally
{
try
{
conn.close();
st.close();
rs.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
A reduced version of your query is :
Select * from users
Where gender = 'F'
And interest1 = 'FISHING'
Or interest2 = 'FISHING'
However, AND has higher priority than OR, so this query is equivalent to :
Select * from users
Where ( gender = 'F' And interest1 = 'FISHING')
Or interest2 = 'FISHING'
What you need to do is add brackets, so :
Select * from users
Where gender = 'F'
And ( interest1 = 'FISHING' Or interest2 = 'FISHING')
By the way, you are also leaving yourself wide open to a SQL injection attack, by including the search terms directly in the SELECT statement ( see What is SQL injection? ).
Much better would be to get in the habit of always using a PreparedStatement.
I got a code, which is searching a whole database. Everything works fine, the only problem is, that I would like to post the whole tuple with integers and chars and so on.
package src;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import java.util.regex.Pattern;
/*
PATTERN MATCHING
*/
public class BigSearch {
public static void main(String[] args) {
try {
String keyword;
String schema = "public";
Boolean caseAware = true;
System.out.println("Insert the term we shall look for in the database.");
Scanner s = new Scanner(System.in);
keyword = s.nextLine();
System.out.println("Do you want the search to be case sensitve "
+ "\n1 - case sensitive"
+ "\n0 - case insensitive");
int caseAwareInt = s.nextInt();
while (caseAwareInt != 0 && caseAwareInt != 1) {
System.out.println("You need to enter 1 or 0. Enter again!");
caseAwareInt = s.nextInt();
}
if (caseAwareInt == 1) {
caseAware = true;
} else if (caseAwareInt == 0) {
caseAware = false;
}
System.out.println("Your search is now case ");
if (caseAware) {
System.out.println("sensitive!");
}
if (!caseAware) {
System.out.println("insensitive!");
}
String like = "";
if (caseAware) {
like = "LIKE";
} else {
like = "ILIKE";
}
Connectivity connectivity = new Connectivity();
conn = connectivity.getConnection();
Statement stmt = conn.createStatement();
Statement stmt2 = conn.createStatement();
Statement stmt3 = conn.createStatement();
Statement stmt4 = conn.createStatement();
Statement stmt5 = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM pg_catalog.pg_tables WHERE schemaname = '" + schema + "';");
ResultSet tablenames = stmt2.executeQuery("SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = '" + schema + "';");
rs.next();
int counttables = rs.getInt(1);
System.out.println("Tabellen im Schema: " + counttables);
int appearance = 0;
int diftables = 0;
for (int i = 0; i < counttables; i++) {
tablenames.next();
ResultSet columnnames = stmt3.executeQuery("SELECT * " +
"FROM information_schema.columns " +
"WHERE table_schema = '" + schema +
"' AND table_name = '" + tablenames.getString(1) +
"' AND data_type = 'character varying'");
ResultSet rss = stmt4.executeQuery("SELECT COUNT(*) " +
"FROM information_schema.columns " +
"WHERE table_schema = '" + schema +
"' AND table_name = '" + tablenames.getString(1) +
"' AND data_type = 'character varying'");
rss.next();
int countcolumns = rss.getInt (1);
System.out.println("Spalten in der Tabelle " + tablenames.getString(1) + ": " + countcolumns);
int count = 0;
for (int i2 = 0; i2 < countcolumns; i2++) {
columnnames.next();
columnnames.getString(1);
System.out.println("Spaltenname: " + columnnames.getString(1));
System.out.println("Tabelle: " + tablenames.getString(1));
ResultSet containsString;
containsString = stmt5.executeQuery("SELECT * "
+ "FROM " + tablenames.getString(1)
+ " WHERE " + columnnames.getString(1) + " " + like + " '%" + keyword + "%'");
while (containsString.next()) {
System.out.println(containsString.getString(1) + " -- contains your keyword");
appearance++;
count ++;
}
}
if (count > 0) {
diftables ++;
}
}
System.out.println("The keyword was found " + appearance + " times in " + diftables + " different tales.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I think the problem is the following code:
while (containsString.next()) {
System.out.println(containsString.getString(1) + " -- contains your keyword");
appearance++;
count ++;
}
So there I am saying getString(1), but I would like to print the full row and because all table have different variable types and different numbers of it, I can't say getString 1, 2, 3, and so on. .getRow doens't work is well.
Any ideas?
There is no way to get all values at once. You need to get them yourself column-by-column. You could use getObject and let the default toString() of that object handle it. The other option is to use the ResultSetMetaData to get the right type of processing, but this might be too complex for your needs.
The getRow doesn't work, because it "Retrieves the current row number.".
Some JDBC drivers will support getString for most datatypes and handle the conversion for you.
I am using writer.println to display each record on a new line. When I am using system.out.println, all the required records are fetched from the database and displayed on the console correctly. However when I am trying to write on to a file, only one record is displayed. Please help.
My codes:
Scanner input = new Scanner(System.in);
System.out.print("Kindly enter the lowest CPA threshold : ");
cpa1 = input.nextFloat();
System.out.println();
System.out.println("Kindly enter highest CPA threshold : ");
cpa2 = input.nextFloat();
String query = "SELECT * FROM student WHERE CPA BETWEEN ? and ? order by CPA asc";
stt = conn.prepareStatement(query);
stt.setFloat(1, cpa1);
stt.setFloat(2, cpa2);
rs = stt.executeQuery();
PrintWriter writer = new PrintWriter("StudentRange.txt");
writer.println("Student ID \t Student Name \t Gender\t CPA\t Enrolment Date");
System.out.println("Student ID \t Student Name \t Gender\t CPA\t Enrolment Date");
while(rs.next()){
String id = rs.getString("student_id");
String name = rs.getString("student_name");
String gender = rs.getString("gender");
float cpa = rs.getFloat("CPA");
Date enrol = rs.getDate("enrollment_date");
try{
writer.println();
writer.println(id + "\t\t" + name + "\t" + gender + "\t" + cpa + "\t" + enrol);
System.out.println(id + "\t\t" + name + "\t" + gender + "\t" + cpa + "\t" + enrol);
writer.close();
}catch(Exception e){
e.printStackTrace();
}
Do not close writer after first line :-)
writer.close();
should be after your while loop ends.
something like:
while(rs.next()){
//... code goes here
}
writer.close();
Follow up question from here
Here is my current code, I try to preform the check to see if they have any tokens and then set the tokens if they dont but it seems to just be running the code no matter if I set it or not.
#EventHandler
public void onJoin(PlayerJoinEvent event) throws SQLException {
Player player = event.getPlayer();
String name = player.getName();
Statement statement = connection.createStatement();
ResultSet res = statement.executeQuery("SELECT * FROM tokens WHERE PlayerName = '" + name + "';");
res.next();
int tokens = 0;
if (res.getString("PlayerName") == null) {
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO tokens (`PlayerName`, `tokens`) VALUES ('" + name + "', '0');");
tokens = 1000;
} else {
tokens = res.getInt("tokens");
}
player.sendMessage(tokens + " Tokens.");
}
The way you check for a row's existence is wrong. Take a look at your query:
"SELECT * FROM tokens WHERE PlayerName = '" + name + "'
If a player does not exist in the table, this query will return 0 rows, not a row with null for the player's name, like you're checking now. Instead, you should check if the ResultSet has a row:
ResultSet res = statement.executeQuery("SELECT * FROM tokens WHERE PlayerName = '" + name + "';");
int tokens = 0;
if (res.next()) {
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO tokens (`PlayerName`, `tokens`) VALUES ('" + name + "', '0');");
tokens = 1000;
} else {
tokens = res.getInt("tokens");
}