`createSQLException` when trying to get all rows in MySQL table - java

I have a simple table consisting of 4 strings and 2 integers (of which one is an ID).
I use a special function to get all rows inside that table:
public Booking[] displayAllBookings() throws ClassNotFoundException, SQLException{
Connection con = connect.getConnection();
PreparedStatement counter = (PreparedStatement) con.prepareStatement("select count(*) from bookings");
ResultSet count = counter.executeQuery();
Booking[] array = new Booking[count.getInt(1)];
String name = null,surname = null,begindate = null,enddate = null;
int persons = 0,i=0;
PreparedStatement posted = (PreparedStatement) con.prepareStatement("SELECT * FROM bookings");
result = posted.executeQuery();
while (result.next()){
begindate = result.getString("begindate");
enddate = result.getString("enddate");
name = result.getString("Name");
surname = result.getString("Surname");
persons = result.getInt("persons");
Booking temp = new Booking(begindate,enddate,name,surname,persons);
array[i++]=temp;
}
return array;
}
But when I execute it I get this exception:
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:790)
at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2472)
at DataBase.DataCommunicatorBooking.displayAllBookings(DataCommunicatorBooking.java:59)
at DataBase.main.displayAll(main.java:125)
at DataBase.main.main(main.java:71)
I've tried looking up this exception but I can't find anything that corresponds to my problem.

You are trying to get the value of the column maxPersons which is not even defined in the table... you meant for sure persons
name = result.getString("Name");
maxPersons = result.getInt("persons");
Room temp = new Room(name,maxPersons);

The problem was with the
PreparedStatement counter = (PreparedStatement) con.prepareStatement("select count(*) from bookings");
ResultSet count = counter.executeQuery();
so I used an ArrayList like so:
public Booking[] displayAllBookings() throws ClassNotFoundException, SQLException{
Connection con = connect.getConnection();
ArrayList<Booking> bookings = new ArrayList<Booking>();
String name = null,surname = null,begindate = null,enddate = null;
int persons = 0,i=0;
PreparedStatement posted = (PreparedStatement) con.prepareStatement("SELECT * FROM bookings");
result = posted.executeQuery();
while (result.next()){
begindate = result.getString("begindate");
enddate = result.getString("enddate");
name = result.getString("Name");
surname = result.getString("Surname");
persons = result.getInt("persons");
Booking temp = new Booking(begindate,enddate,name,surname,persons);
bookings.add(temp);
}
return bookings.toArray(new Booking[bookings.size()]);
}
and that solved the problem;

This is because the column "maxPersons" does not exist, you probably ment "persons"

Related

Convert jsonb postgres column data to String

I have a column of jsonb in Postgres.
Which contains data like "{\" name\":\"xyz\"}". I want to convert it as {"name":"xyz"}.
How can I achieve this?
Could you please clarify what exactly you want to do?
If you need to remove whitespaces in Java you can try something like this.
try (final Connection connection = embeddedPostgres.getTestDatabase().getConnection();
final Statement statement = connection.createStatement();
final PreparedStatement updateStatement = connection.prepareStatement("update your_table set your_column = ? where id = ?")) {
connection.setAutoCommit(false);
try (final ResultSet resultSet = statement.executeQuery("select * from your_table order by id limit 10")) {
while (resultSet.next()) {
final long id = resultSet.getLong("id");
final String infoAsString = resultSet.getString("info");
final String withoutWhitespaces = StringUtils.deleteWhitespace(infoAsString);
final PGobject fixedInfoObject = new PGobject();
fixedInfoObject.setType("jsonb");
fixedInfoObject.setValue(withoutWhitespaces);
updateStatement.setObject(1, fixedInfoObject);
updateStatement.setLong(2, id);
updateStatement.executeUpdate();
}
}
connection.commit();
}

Update data in table

The thing i want to achieve here is that i have a table name total_product in mysql database and i want to retrieve the value of SNo = 1 from the table and update the Quantity in the table.
There is a text box i am using in GUI in which the additional product produced will be written.
The output from the table is stored in variable id and the new quantity that is produced is stored in the variable q1.
so the new product quantity will be q1 = q1 + id.
I am not able to understand what should i put in the sql statement that is used in stmt.executeUpdate(sql) because the sql is a string and i have to pass an integer value to Qunty in the sql string.
Please Help.
Connection conn = null ;
Statement stmt = null ;
String url = "jdbc:mysql://localhost:3306/project";
String user = "root";
String password = ".dpadpep";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url,user,password);
String sql = "Select Qunty from total_product " + "where SNo = 1";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
int id=0;
int q1 = Integer.parseInt(fld1[0].getText());
while(rs.next()) {
id = rs.getInt(1);
System.out.println("Quantity="+id);
}
q1 = q1+id;
sql = "UPDATE total_product " + "set Qunty = q1 where SNo=1";
stmt.executeUpdate(sql);
You don't need to explicitly retrieve the current value in the database, you can simply add the additional amount directly:
int q1 = Integer.parseInt(fld1[0].getText());
String sql = "UPDATE total_product SET Qunty = Qunty + ? WHERE SNo = 1";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, q1);
ps.executeUpdate();

Inserting Data into Sql Using Java Netbeans

I want to insert input given by user into Sql Table using Java, but dont know how many coloumn is need.
eg.
insert into table_name values('"+id+"','"+name+"')
this query is not going to work because I don't know the column name i.e ID, name.
I want the query that is universal for any inserting data.
As per my need I tried this code. I HOPE IT WORKED FOR ALL.
void getTableInput(String tname, String dname) throws ClassNotFoundException, SQLException {
this.tname = tname;
this.dname = dname;
Scanner s = new Scanner(System.in);
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String conURL = "jdbc:sqlserver://localhost:1433;databaseName=" + this.dname + ";user=JT_DATA;password=1234";
Connection con = DriverManager.getConnection(conURL);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM " + this.tname);
ResultSetMetaData rsmd = rs.getMetaData();
int colNo = rsmd.getColumnCount();
String colName[] = new String[colNo];
String[] get_User_Input = new String[100];
for (int i = 1; i <=colNo; i++)
{
colName[i-1] = rsmd.getColumnLabel(i);
System.out.print(Arrays.toString(colName) + " : ");
get_User_Input[i-1] = s.next();
}
String store="";
for(int i=0;i<colNo;i++)
{
store += "'"+get_User_Input[i]+"',";
}
store = store.substring(0,store.length() -1);
PreparedStatement pst = con.prepareStatement("insert into "+this.tname+" values ("+ store +")");
pst.executeUpdate();
System.out.println("Data Inserted");
}
But the problem with this is that. This can only insert String Datatype.
I dont think there is any universal query.
If you dont know column name than you can find name of the column by using meta data.
You can get meta data of the connections (database)
DatabaseMetaData databaseMetaData = connection.getMetaData();
You can also get list of the tables.
String catalog = null;
String schemaPattern = null;
String tableNamePattern = null;
String[] types = null;
ResultSet result = databaseMetaData.getTables(
catalog, schemaPattern, tableNamePattern, types );
while(result.next()) {
String tableName = result.getString(3);
}
Listing column name in table.
String catalog = null;
String schemaPattern = null;
String tableNamePattern = "my_table";
String columnNamePattern = null;
ResultSet result = databaseMetaData.getColumns(
catalog, schemaPattern, tableNamePattern, columnNamePattern);
while(result.next()){
String columnName = result.getString(4);
int columnType = result.getInt(5);
}
In this way you can find column name and can create query dynamically.

How return row_number use prepared Statement with StringBuffer in Java

I want the return row_number press the Variable Model class:
Whereas the PreparedStatament in the examples I exploreri, rferencia the column name. row_number is not a native or physical column of the table. How to make the values dete method are returned as if they were an actual physical table column. Nor would it be interesting to create a new column in the table to just store these values. I also do not intend to use triggers to return these values. It can be done this way is without error in the code below.
final StringBuffer lSql = new StringBuffer();
lSql.append("SELECT ");
lSql.append(" TABLE_NAME.ROW_NUMBER() OVER (ORDER BY COLUMN_DAY) ");
lSql.append("FROM ...");
// ...
final List<classModel> listData = new ArrayList<classModel>();
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rset = null;
try{
conn = getConnection1();
stmt = conn.prepareStatement(lSql.toString());
int count = 1;
//stmt.setLong(count++, classModelParameterThisFunctionDAO.getVarColumnSequence());
//...
rset = stmt.executeQuery(); // ERROR THIS LINE NI DEBUG
while(rset.nex()){
final classModel lClassModel = new classModel();
lClassModel.setColumnSequence(rset.getInt("ROW_NUMBER() OVER (ORDER BY COLUMN_DAY)")); //error in this line
listData.add(lClassModel);
lSql.append("SELECT ");
lSql.append(" TABLE_NAME.ROW_NUMBER() OVER (ORDER BY COLUMN_DAY) as RRN ");
lSql.append("FROM ...")
.
.
.
lClassModel.setColumnSequence(rset.getInt("RRN"));

Java Import Excel Data into MySQL about encoding

here my source!!
String url = "jdbc:mysql://localhost/dahan?characterEncoding=euckr";
String user = "root";
String password = "pass";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection(url,user,password);
con.setAutoCommit(false);
PreparedStatement pstm = null ;
PreparedStatement pstm1 = null ;
PreparedStatement pstm2 = null ;
FileInputStream input = new FileInputStream("C:/Users/hyunwoo/Downloads/Personal Contacts.xls");
POIFSFileSystem fs = new POIFSFileSystem( input );
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
Row row;
String del = "DROP TABLE IF EXISTS `dahanMail`";
String cre = "CREATE TABLE `dahanMail` (`전체이름` varchar(50),`성` varchar(50),`이름` varchar(50) ,`닉네임` varchar(50),"
+ "`회사` varchar(500),`부서` varchar(500),`직급` varchar(500),`메일주소1` varchar(50),"
+ "`메일주소2` varchar(50),`전화번호1` varchar(50),`전화번호2` varchar(50),`전화번호3` varchar(50),"
+ "`휴대폰1` varchar(50),`휴대폰2` varchar(50),`팩스1` varchar(50),`팩스2` varchar(50),"
+ "`주소` varchar(50),`웹사이트` varchar(50),`id` int NOT NULL ,PRIMARY KEY (`id`))";
pstm1 = (PreparedStatement) con.prepareStatement(del);
pstm2 = (PreparedStatement) con.prepareStatement(cre);
pstm1.execute();
pstm2.execute();
for(int i=0; i<=sheet.getLastRowNum(); i++){
row = sheet.getRow(i);
String fullname = row.getCell(0).getStringCellValue();
String lastname = row.getCell(1).getStringCellValue();
String firstname = row.getCell(2).getStringCellValue();
String nickname = row.getCell(3).getStringCellValue();
String company = row.getCell(4).getStringCellValue();
String sub = row.getCell(5).getStringCellValue();
String hei = row.getCell(6).getStringCellValue();
String mailaddress1 = row.getCell(7).getStringCellValue();
String mailaddress2 = row.getCell(8).getStringCellValue();
String cnumber1 = row.getCell(9).getStringCellValue();
String cnumber2 = row.getCell(10).getStringCellValue();
String cnumber3 = row.getCell(11).getStringCellValue();
String pnumber1 = row.getCell(12).getStringCellValue();
String pnumber2 = row.getCell(13).getStringCellValue();
String fax1 = row.getCell(14).getStringCellValue();
String fax2 = row.getCell(15).getStringCellValue();
String address = row.getCell(16).getStringCellValue();
String website = row.getCell(17).getStringCellValue();
int id = (int) row.getCell(18).getNumericCellValue();
String sql = "INSERT INTO dahanmail VALUES('"+fullname+"','"+lastname+"','"+firstname+"'"
+ ",'"+nickname+"','"+company+"','"+sub+"','"+hei+"','"+mailaddress1+"','"+mailaddress2+"','"+cnumber1+"','"+cnumber2+"','"+cnumber3+"'"
+ ",'"+pnumber1+"','"+pnumber2+"','"+fax1+"','"+fax2+"',"
+ "'"+address+"','"+website+"','"+id+"')";
pstm = (PreparedStatement) con.prepareStatement(sql);
pstm.execute();
System.out.println("Import rows "+i);
}
con.commit();
pstm.close();
con.close();
input.close();
System.out.println("Success import excel to mysql table");
I have saved the excel data to mysql using the POI in Java
and It works well!
so I checked the mysql table in cmd
but console window still show broken language like "???"
it seems to be encoding problem...
How can I change the source to fix the encoding problem?
What you have looks like it's close to working, but there are some things I would change:
Firstly, declare your SQL before the loop, with ?'s for value placeholders:
String sql = "INSERT INTO dahanmail VALUES(?,?,?)";
PreparedStatement pstm = conn.prepareStatement(sql);
(I have not put enough ?s in the code above, there should be one for each value)
Then, in the loop, you can set the parameters:
pstm.setString(1,row.getCell(0).getStringCellValue());
pstm.setString(2,row.getCell(2).getStringCellValue());
//one for each value. You could use another loop.
Then (still in the loop), execute the statement:
pstm.execute();
Finally clear the parameters for next time round:
pstm.clearParameters();

Categories