when i run this program i got this in the output screen.I don't know what is the problem is there any thing i am missing.
import org.apache.cassandra.cql.jdbc.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.*;
import javax.sql.*;
public class Operations
{
public static void main(String[] args){
try
{
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
Connection con = DriverManager.getConnection("jdbc:cassandra://localhost:9160/temp");
//String name = "name";
String qry = "select name FROM tempcql where key = detail";
Statement smt = con.createStatement();
ResultSet resultSet = smt.executeQuery(qry);
while(resultSet.next())
{
System.out.println(resultSet.getString("name"));
}
}
catch(Exception e)
{
System.out.println(" : "+e.getMessage());
}
}
}
here is the output of this : java.nio.HeapByteBuffer[pos=86 lim=91 cap=159]
You could try getting the bytes and converting that to a String:
String name_result = new String(resultSet.getBytes("name"), "UTF-8");
System.out.println(name_result);
Try using single quotes in your SQL string:
String qry = "select name FROM tempcql where key = 'detail'";
You are getting the value in the binary format.But you specified column type as string.Instead you need to say as follows:
ObjectInputStream is = rs.getBinaryStream("name");
ByetBuffer bb = (ByteBuffer)is.readObject();
Related
i want to display messages with the sender name. The outer while loop is working fine but there is some problem in the inner while loop. I have tried a lot to figure out but got no result. Can anyone help me? I'll very thankful.
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
public class Messages extends Login {
static Scanner in = new Scanner(System.in);
public static void main(String args[]) throws Exception{
boolean isLoggedin = login();
String msg = "";
String senName = "";
if(isLoggedin) {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo?verifyServerCertificate=false&useSSL=false", "root", "");
Statement st = con.createStatement();
Statement st1 = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM chat");
ResultSet rs1 = st1.executeQuery("SELECT * FROM data");
while(rs.next()) {
int dbRecID = rs.getInt("reciever_id");
if(dbRecID == user_id) {
msg = rs.getString("message");
int dbSenID = rs.getInt("sender_id");
while(rs1.next()) {
int senID = rs1.getInt("id");
if(senID == dbSenID) {
senName = rs1.getString("name");
}
}
System.out.println(senName+" sent you a message: "+msg);
}
}
}
else {
System.out.print("Login Unsuccessful");
}
}
}
Output
Ali Ahmed sent you a message: How are you?
Ali Ahmed sent you a message: Hi!
Required Output
Ali Ahmed sent you a message: How are you?
Hamza sent you a message: Hi!
The issue comes from the two nested while loops.
The query ResultSet rs1 = st1.executeQuery("SELECT * FROM data"); is executed just once.
The first time you loop on while(rs.next()) you will fetch the whole content of rs1 to check if the sender id is the right one.
Then on the second iteration on while(rs.next()) because rs1 has been already fetched while(rs1.next()) wil return false.
In order to have your code working you should move the execution of the second query to get something like this:
while(rs.next()) {
...
ResultSet rs1 = st1.executeQuery("SELECT * FROM data");
while(rs1.next()) {
...
}
...
}
But I think that it would be a better solution to make just one SQL
request joining the datas of the two tables and including the where
condition.
I keep getting the following error when I try to upload my books table through eclipse:
java.sql.SQLSyntaxErrorException: ORA-01722: invalid number
I have been able to upload other tables in my database using this basic code, just not this one.
I think it might be something to do with how I am uploading my dates, but I am not sure.
package uploadDatabase;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import oracle.jdbc.OracleDriver;
import java.sql.DatabaseMetaData;
import java.sql.Date;
public class StatesTable {
public static void main(String[] args) {
//private static Connection connection;
try{
DriverManager.registerDriver(new OracleDriver());
//make strings for database connections
String url = "jdbc:oracle:thin:#localhost:1521:xe";
String userName = "BOOKSTORE";
String password = "***********";
//make database connection
Connection conn = DriverManager.getConnection(url,userName,password);
DatabaseMetaData meta = conn.getMetaData();
System.out.println(meta.getDatabaseProductVersion());
String isbn[] = {"00000000110","00000000111","00000000112","00000000113","00000000114"};
String title[] = {"THE SHINING", "THE GIRL WITH THE DRAGON TATTO", "PRIDE AND PREJUDICE", "BOSSYPANTS", "THE HUNGER GAMES"};
String author[] = {"STEPHEN KING", "STIEG LARSSON", "JANE AUSTEN", "TINA FEY", "SUZANNE COLLINS"};
String publishDate[] ={"19750115","19990805","18731015","20160105","19821115"};
String edition[] = {"6TH","3RD","26TH","1ST","7TH"};
double cost[] = {15.75,17.95,8.95,9.95,12.95};
String genre[] = {"HORROR", "MYSTERY", "ROMANCE","COMEDY", "ACTION"};
//Database statement for inserting values into BOOKS table
String sqlStatement = "INSERT INTO BOOKS VALUES(?,?,?,?,?,?,?)";
//Prepared statement for database connection
PreparedStatement pstmt = conn.prepareStatement(sqlStatement);
//loop uploads data into database;
for(int i = 0; i < 5; i++){
//insert values into dbms statement
String isb = isbn[i];
String tit = title[i];
String auth = author[i];
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
java.util.Date parsed = df.parse(publishDate[i]);
Date publishDat = new Date(parsed.getTime());
System.out.println(publishDat);
String editio = edition[i];
double cos = cost[i];
String gen = genre[i];
pstmt.setString(1,isb);
pstmt.setString(2,tit);
pstmt.setString(3,auth);
pstmt.setDate(4,publishDat);
pstmt.setString(5,editio);
pstmt.setDouble(6, cos);
pstmt.setString(7, gen);
//Execute update
pstmt.executeUpdate();
}
//close pstmt statement
pstmt.close();
//close database connection
conn.close();
}
catch(SQLException e){
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
The reason you are getting this error is because one of the column data types you are passing into the insert command is not the same as what is actually defined. Make sure to check your table and it's column values and data types and make sure those data types align with which you are trying to insert into that database. As what Andreas said in the comment below you should ALWAYS name your columns in INSERT statements, without them you will not know what is going into your database. Hope this helps :)
I'm using the jtbs.jdbc.Driver to verify that a proxy number is stored in my MySQL database.
The problem is that whenever I try to copy the curtain row from the table and put it in my ResultSet, the error says that
there is no current row in the ResultSet
The error is at line 31 String value = result.getString(i);
i have been looking all over the web for answers but none of them seem to help my specific predicament.
UP DATE
so far i added a while(result.next()) and it basically dose nothing the while(result.next()) dose not execute.
Here's my code!!!
package dataBata;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
public class apples {
ArrayList<String> myList = new ArrayList<String>();
String proxNumber = "2435847564";
String usersName = "user";
String password = "pass";
public void wrightMatchdb(){
Connection conn = null;
String url = "jdbc:jtds:sqlserver://localhost:1433/model";
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn = DriverManager.getConnection(url, usersName, password);
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery("select replace(PROXID , ' ','') PROXID ,FIRST_NAME from OKWC_IDCARDS where PROXID = '" + proxNumber + "'");
System.out.println("hello");
while(result.next()){
for(int i=1;i<=6;i++){
System.out.println("hello2");
String value = result.getString(i);
if(result.getString(i) != null){
value = value.replace(" ","");
myList.add(value);
}
String userProx=myList.get(i);
String userFName=myList.get(i+1);
JOptionPane.showMessageDialog(null, userProx + " has a match for", "hi " + userFName, JOptionPane.DEFAULT_OPTION);
}
System.out.println("hello3");
};
System.out.println("hello4");
statement.close();
}
catch (Exception e){
e.printStackTrace();
}
finally {
if (conn != null) try { conn.close(); } catch(Exception e) {}
}
}
public static void main(String[] args){
apples A = new apples();
A.wrightMatchdb();
}
}
You need to call result.next() before calling result.getString(i)
Moves the cursor forward one row from its current position. A
ResultSet cursor is initially positioned before the first row; the
first call to the method next makes the first row the current row; the
second call makes the second row the current row, and so on.
As far as I can see, your query returns only 2 columns so if you call result.getString(i), make sure that i is either 1 or 2 otherwise you will get an exception.
Actually, i got a stress in this problem.
I have an image
So Im getting 2 problems here.
How can I insert the auto generate id with format starting "T00001"?
How can i count total number of ID when i display with datas in table.
Im a new one in Java MVC GUI. Anyone can help me get a good solution.
Thanks in advanced
And this is my Data Access Object file.
package model;
import java.sql.*;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class SchoolDAO{
Conexion conexion;
public SchoolDAO(){
conexion = new Conexion();
}
/////INSERT TEACHER
public String insertTeacher(String tbno, String tbname, String tbphone, String tbqualification, String tbexp){
String rptaAdd = null;
try {
Connection accessDB = conexion.getConexion();
CallableStatement cs = accessDB.prepareCall ("{call teacher_insert(?,?,?,?,?)}");
cs.setString(1, tbno);
cs.setString(2, tbname);
cs.setString(3, tbphone);
cs.setString(4, tbqualification);
cs.setString(5, tbexp);
int numFAeffect = cs.executeUpdate();
if(numFAeffect>0){
rptaAdd ="Add successful.";
}
} catch (Exception e){
JOptionPane.showMessageDialog(null, e.toString());
}
return rptaAdd;
}
public ArrayList<School> listTeacher(){
ArrayList listaTeacher = new ArrayList();
School school;
try{
Connection accessDB = conexion.getConexion();
PreparedStatement ps = accessDB.prepareStatement("select * from teacher");
ResultSet rs = ps.executeQuery();
while(rs.next()){
school = new School();
school.setTno(rs.getString(1));
school.setTname(rs.getString(2));
school.setTphone(rs.getString(3));
school.setTqualification(rs.getString(4));
school.setTexp(rs.getString(5));
listaTeacher.add(school);
}
}catch (Exception e){
}
return listaTeacher;
}
}
Send the ID as a number incremented from a sequence or other mechanism that will get you auto incrementing numbers with "T" + left padded string with zeroes to the desired value.
"T" + StringUtils.leftpad(id + "", 5, "0"); // your ID
Select the count (*) from teacher table.
I made a class Test which counts the number of entries corresponding to the user id in the database (calling each entry an email). I used 11120059 as id and number of entries corresponding to this in the database is 2. The output of countMail function is working perfectly but because i am returning an array from getMail() function and taking it into new array, it is showing me null pointer exception. Please help I am stuck in middle of this. The code is:
package src.service;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import model.Email;
import model.User;
public class Test {
public int countMail(User user){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Get a connection to the database
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/chillmaarodb", "root", "rsystems");
PreparedStatement myStatement = myConn.prepareStatement("select * from complaints where RID=? ORDER BY date desc");
myStatement.setString(1, user.getId());
ResultSet rs = myStatement.executeQuery();
int count=0;
while(rs.next())
{
count++;
}
return count;
}
catch(Exception e){
e.printStackTrace();
}
return 0;
}
public Email[] getMail(User user){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Get a connection to the database
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/chillmaarodb", "root", "rsystems");
PreparedStatement myStatement = myConn.prepareStatement("select * from complaints where RID=? ORDER BY date desc");
myStatement.setString(1, user.getId());
ResultSet rs = myStatement.executeQuery();
Home home= new Home();
int length = home.countMail(user);
Email[] mail = new Email[length];
int i=0;
while(rs.next())
{
mail[i].setMessage((String) rs.getString(5));
mail[i].setTitle((String) rs.getString(4));
mail[i].setSender((String) rs.getString(2));
mail[i].setReceiver((String) rs.getString(1));
i++;
}
return mail;
}
catch (Exception e){
e.printStackTrace();
}
Email[] dummyMail = new Email[1];
return dummyMail;
}
public static void main(String[] args){
Test test = new Test();
User user = new User();
user.setId("11120059");
System.out.println(test.countMail(user));
Email[] email = test.getMail(user);
for (int i=0 ; i<test.countMail(user) ; i++){
System.out.println(email[i].getSender());
}
}
}
And the output is:
2
java.lang.NullPointerException
at src.service.Test.getMail(Test.java:73)
at src.service.Test.main(Test.java:107)
Exception in thread "main" java.lang.NullPointerException
at src.service.Test.main(Test.java:111)
When you write Email[] mail = new Email[length]; you create an array of given length which contains null references. You cannot automatically create all the objects for that array by this command. Add mail[i] = new Email() statement:
Email[] mail = new Email[length];
int i=0;
while(rs.next())
{
mail[i] = new Email(); // or use appropriate constructor parameters
mail[i].setMessage((String) rs.getString(5));
mail[i].setTitle((String) rs.getString(4));
mail[i].setSender((String) rs.getString(2));
mail[i].setReceiver((String) rs.getString(1));
i++;
}
Also note that when you create a dummyMail array, it's also an array with single null-reference, the Email object is not created there as well. Probably you need:
Email[] dummyMail = new Email[] {new Email()};