I am trying to Create a table Model (i, y1, y2 .... yd) in Vertica using JAVA. Column i is integer and all others are REAL. I used the following code to create it. However it is showing syntax error at or near null. Does anybody know what that means? The connection works for the program.
public void createMODEL(int d)
{
int x;
try
{
Statement stmt = conn.createStatement();
String createquery = "CREATE TABLE MODEL ( "
+ "i integer primary key ";
for (x=1;x<=d;x++) createquery+= " , " + Y[x] + " REAL ";
createquery += ")";
stmt.executeUpdate(createquery);
}
catch (Exception e)
{
System.out.println("Error while executing create model query");
System.out.print(e);
System.exit(0);
}
}
Y is defined as follows -
String Y[]=new String[100];
I guess you should check if Y[x] is not null:
Statement stmt = conn.createStatement();
String createquery = "CREATE TABLE MODEL ( "
+ "i integer primary key ";
for (x=1;x<=d;x++) {
if (Y[x] != null) createquery+= " , " + Y[x] + " REAL ";
}
createquery += ")";
stmt.executeUpdate(createquery);
This works for me for MySQL. Try this.
String Y[] = new String[100];
Y[0] = "h";
Y[1] = "ha";
Y[2] = "hat";
Y[3] = "hati";
Y[4] = "hatim";
System.out.println("Your columns array : " + Arrays.deepToString(Y));
String createquery = "CREATE TABLE MODEL ( " + "i integer primary key ";
for (int i = 0; i < Y.length; i++) {
if (Y[i] != null)
createquery += " , " + Y[i] + " REAL ";
}
createquery += ");";
System.out.println("Your create query : " + createquery);
Related
So I want to count the total number of sales for each seller from two different tables.
And I wrote down the code but it does not work..... Can anyone please help me???
So it should produce that sellerID =1 and count = 13. sellerID=2 and count= 14. Something like this. So I want to produce 3 total amount of sales for each seller, but the output shows the red lines ....
String[] sellerID = {"1","2","3"};
int num = 0;
String []totalAmountSale = new String[3];
String sql = "SELECT tblOrder.SellerID, COUNT(*) " +
"FROM tblOrder, tblSeller " +
"WHERE tblOrder.SellerID = tblSeller.SellerID " +
"GROUP BY tblOrder.SellerID"
+ "ORDER BY tblOrder.SellerID;";
ResultSet rs = db.query(sql);
try {
while(rs.next())
{
totalAmountSale[num]= ""+rs.getInt(2);
num++;
}
rs.close();
} catch (SQLException ex) {
Logger.getLogger(DatabaseWork.class.getName()).log(Level.SEVERE, null, ex);
}
String out = "";
for (int i = 0; i < 3; i++) {
out+= totalAmountSale[i]+"\n";
}
JOptionPane.showMessageDialog(null,out );
}
You miss a space:
String sql = "SELECT tblOrder.SellerID, COUNT(*) " +
"FROM tblOrder, tblSeller " +
"WHERE tblOrder.SellerID = tblSeller.SellerID " +
"GROUP BY tblOrder.SellerID "
+ "ORDER BY tblOrder.SellerID;";
This is of course parts of a larger code. It will compile with no problem, but when I call this method I get the error
"syntax error near or at "."" at the position of stmt.executeQuery(SQL).
I would really appreciate the help!
private void Component() {
try {
Statement stmt = con.createStatement();
String SQL = "SELECT component.*, stock.amount_of_component, component.price component.component_type "
+ "FROM component JOIN stock "
+ "ON component.id = stock.component_id "
+ "ORDER BY component.component_type";
ResultSet rs = stmt.executeQuery(SQL);
rs.next();
int id = rs.getInt("ID");
int amount_of_component = rs.getInt("Amount");
String name = rs.getString("Name");
double price = rs.getDouble("Price");
String component_type = rs.getString("Type");
System.out.println(" " + id + amount_of_component + " " + name + " " + price + " " + component_type);
} catch (SQLException err)
{
System.out.println(err.getMessage());
}
}
Typo, missing a comma in the query between component.price and component.component_type :
SELECT component.*, stock.amount_of_component, component.price, component.component_type
FROM component JOIN stock
ON component.id = stock.component_id
ORDER BY component.component_type
Edit: To read the whole result set, put this cycle instead of rs.next()
while(result.next()) {
int id = rs.getInt("ID");
int amount_of_component = rs.getInt("Amount");
String name = rs.getString("Name");
double price = rs.getDouble("Price");
String component_type = rs.getString("Type");
System.out.println(" " + id + amount_of_component + " " + name + " " + price + " " + component_type);
}
Edit2: To print the header, you have to do it manually by putting a System.out.println(" id amount_of_component name price component_type "); before the while.
You missed a comma between 'component.price' and 'component.component_type'
I've got this error from my jdbc driver. I don't know why, tho.
Here's the corresponding code:
try {
String colNames = " ";
for (int i=0; i<cols.size(); i++) {
if (i == cols.size()-1) {
colNames += cols.get(i);
} else if (i<cols.size()) {
colNames += cols.get(i)+", ";
}
}
String colValues = " ";
for (int i=0; i<values.size(); i++) {
if (i == values.size()-1) {
colValues += values.get(i);
} else if (i<values.size()) {
colValues += values.get(i) + ", ";
}
}
System.out.println(
"INSERT INTO `" + tableName + "` (" + colNames + ") VALUES (" + colValues + ") "
);
//System.out.println(kerdojel);
PreparedStatement pst = connHandler.conn.prepareStatement
("INSERT INTO `" + tableName + "` (" + colNames + ") VALUES (" + colValues + ") ");
pst.executeUpdate();
pst.close();
}
"values" and "cols" are ArrayLists that contains the data from the JTable.
cols are the Column names and values are the cell values.
The output for the Sysout:
INSERT INTO `TableOne` ( nev, kor, lakhely) VALUES ( asd, 1, asd)
The error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'asd' in 'field list'
That is not how the PreaparedStatement was intended to be used. When you use a PreparedStatement, you can specify the values by using one of the "set" methods.
Here is an example:
String colNames = " ";
String colValues = " ";
for (int i=0; i<cols.size(); i++) {
if(i!=0){
colNames += ", ";
colValues += ", ";
}
colNames += cols.get(i);
colValues += "?";
}
try (PreparedStatement pst = connHandler.conn.prepareStatement("INSERT INTO `" + tableName + "` (" + colNames + ") VALUES (" + colValues + ") ");){
for (int i = 0; i < values.size(); i++) {
pst.setString(i+1,values.get(i));
}
pst.executeUpdate();
}
You should use the appropriate "set" method based on the column's data type (setInt(...), setDate(...), etc.). You can find more details here
Try to use command like these one to check problem existed.
PREPARE mycmd FROM 'INSERT INTO TableOne(nev,kor) VALUES (?, ?)'
I am trying to create an insertion in some tables with random data but i have a problem with the duplicates.
I wrote an insertion of random records in postgresql b but it returns duplicates detection and there should be no duplicates i am using every name for exactly 2680 times and the names are 22 for 58960 records total of table play_in please check and tell what's wrong with it and how does produce a duplicate.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Random;
public class PostgreSQLJDBC {
public static void main(String args[]) {
Connection c = null;
Statement stmt = null;
int year;
int year1;
int num_rating;
int num_ratingAvg;
String[] round = new String[5];
round[0] = "32nd";
round[1] = "16th";
round[2] = "quarter_final";
round[3] = "SemiFinal";
round[4] = "FInal";
String[] name1 = new String[22];
name1[0] = "ahmed";
name1[1] = "mohamed";
name1[2] = "mai";
name1[3] = "salma";
name1[4] = "walid";
name1[5] = "wael";
name1[6] = "fadwa";
name1[7] = "nada";
name1[8] = "nahla";
name1[9] = "mustafa";
name1[10] = "ola";
name1[11] = "omar";
name1[12] = "amr";
name1[13] = "beshoy";
name1[14] = "marina";
name1[15] = "gerges";
name1[16] = "botros";
name1[17] = "mina";
name1[18] = "menna";
name1[19] = "feasal";
name1[20] = "youssef";
name1[21] = "moussa";
Random id = new Random();
Random roundc = new Random();
String round1;
int idc;
String name;
Random namec = new Random();
int namecounter = 0;
Random belle = new Random();
int belec = 0;
Random yearc = new Random();
Random num_ratingsc = new Random();
int num_ratingSum = 0;
// roundc.nextInt(4);
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/a2", "mohamed", "1234");
System.out.println("Opened database successfully");
String sql3;
String sql4;
stmt = c.createStatement();
String sql = "CREATE TABLE cup_matches "
+ "(MID INT PRIMARY KEY NOT NULL,"
+ " ROUND TEXT NOT NULL, "
+ " YEAR INT NOT NULL, "
+ " NUM_RATINGS INT NOT NULL, "
+ " RATING INT NOT NULL)";
String sql1 = "CREATE TABLE played_in "
+ "(MID INT NOT NULL,"
+ " NAME TEXT NOT NULL, "
+ " YEAR INT NOT NULL, "
+ " POSITION INT NOT NULL, "
+ "CONSTRAINT pk_played_in PRIMARY KEY (MID, NAME));";
String sql2 = "ALTER TABLE played_in ADD CONSTRAINT ref FOREIGN KEY (MID) REFERENCES cup_matches (MID);";
stmt.executeUpdate(sql);
stmt.executeUpdate(sql1);
stmt.executeUpdate(sql2);
for (int i = 0; i < 2680; i++) {
year = yearc.nextInt(2014 - 1900) + 1900;
num_rating = num_ratingsc.nextInt(1000);
num_ratingSum += num_rating;
num_ratingAvg = num_ratingSum / (i + 1);
round1 = "\'" + round[roundc.nextInt(4)] + "\'";
sql3 = "INSERT INTO cup_matches (MID, ROUND, YEAR, NUM_RATINGS, RATING) "
+ "VALUES ("
+ i
+ ", "
+ round1
+ ", "
+ year
+ ", "
+ num_rating + ", " + num_ratingAvg + ");";
stmt.executeUpdate(sql3);
System.out.println(sql3);
}
for (int j = 0; j < 58960; j++) {
idc = j;
idc = (idc >= 2679) ? 0 : idc;
year1 = yearc.nextInt(2014 - 1900) + 1900;
num_rating = num_ratingsc.nextInt(1000);
if ((belle.nextInt(2 - 1) + 1) == 1 && belec < 118) {
name = "\'" + name1[namecounter] + "belle" + "\'";
sql4 = "INSERT INTO played_in (MID, NAME, YEAR, POSITION) "
+ "VALUES (" + idc + ", " + name + ", " + year1
+ ", " + num_rating + ");";
stmt.executeUpdate(sql4);
belec++;
idc++;
System.out.println(idc + " " + namecounter);
namecounter++;
} else {
name = "\'" + name1[namecounter] + "\'";
sql4 = "INSERT INTO played_in (MID, NAME, YEAR, POSITION) "
+ "VALUES (" + idc + ", " + name + ", " + year1
+ ", " + num_rating + ");";
stmt.executeUpdate(sql4);
namecounter++;
idc++;
System.out.println(idc + " " + namecounter);
}
namecounter = (namecounter < 22) ? namecounter : 0;
}
// stmt.executeUpdate(sql);
// stmt.executeUpdate();
// stmt.executeUpdate(sql2);
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Table created successfully");
}
}
This line:
idc = (idc >= 2679) ? 0 : idc;
is causing you problems as you later use idc as the value for mid, which is your primary key. This line returns 0 when idc is >= 2679, which will give you duplicate key errors.
This line makes idc = 0 for each j value above 2679.
idc = j;
idc = (idc >= 2679) ? 0 : idc;
The first time, it will insert in the table played_in with idc = 0 and will insert that value for each name, when the name counter starts again with 0:
namecounter = (namecounter < 22) ? namecounter : 0;
It will try to insert the first name with 0 again and it will fail due to duplicate key error
I'm wanting to insert an entry if it does not exist otherwise update the entry, I couldn't use the ON DUPLICATE KEY UPDATE, I got confused with the syntax. So I tried to do something like this:
final String QUERY = "REPLACE INTO skills SET VALUES (" + insert(player) + ") WHERE playername = '" + player.getUsername() + "'";
statement.execute(QUERY);
statement.close();
connection.close();
}
private static String insert(Player player) {
String stringToReturn = "'" + player.getUsername() + "',";
for (int index = 0; index < 25; index++) {
stringToReturn += player.getSkills().getLevels()[index] + "," + ((int) player.getSkills().getXp()[index]) + ",";
}
stringToReturn = stringToReturn.substring(0, stringToReturn.length() - 1);
return stringToReturn;
}
But that's incorrect syntax so I was wondering how I could do this?
playername is primary key
I think the correct syntax to make ON DUPLICATE KEY UPDATE work for you is:
"INSERT INTO skills (playerName, otherColumn)
VALUES ('" + player.getUsername() + "', '" + insert(player) +"')
ON DUPLICATE KEY UPDATE otherColumn = VALUES(otherColumn)";