i am using cassandra-jdbc to perform the operation on data in cassandra but when i run this simple program i get exception.
this is my code:
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 qry = "select name FROM cql";
Statement smt = con.createStatement();
ResultSet resultSet = smt.executeQuery(qry);
System.out.println(resultSet);
while(resultSet.next())
{
System.out.println(resultSet);
}
}
catch(Exception e)
{
System.out.println(" : "+e.getMessage());
}
}
}
i got :cannot parse 'name' as hex bytes
Try:
import static org.apache.cassandra.utils.Hex.bytesToHex;
...
String name = bytesToHex("name".getBytes());
String qry = "select '" + name + "' FROM cql";
Related
Can anybody help me to get actual column name and its alias using ResultSetMetaData by connecting to sqlserver database.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
class MysqlCon {
public static void main(String args[]) {
Connection con = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=alcoa", "sa", "test");
Statement stmt = con.createStatement();
String query = "SELECT std_code as \"Student code\" from Student ";
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsm =rs.getMetaData();
for (int i = 1; i <= rsm.getColumnCount(); i++) {
System.out.println(rsm.getColumnLabel(i) + "--" + rsm.getColumnName(i));
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
output
Student code--Student code
Above code works as expected in other database like mysql and oracle.
I checked code for SQLServerResultSetMetaData. Both methods getColumnLabel and getColumnName are identical.
abzycdxw65, has raised same issue on their github account. it is closed.
Is there any way to get following output:
Student code--std_code
If I get your question you can try the followings to retrieve column names
select name from sys.columns
I have a JSF webapp and I encountered one problem. I want to take data that is from one table and is inserted in a datatable and insert it into a log table in the database.
I did the connection with the database but it doesn't show any errors and it doesn't insert anything.
I went in with the debugger from netbeans and the variables that I want to insert have values. I do not know where the problem is.
Here is the code:
package com.spv.raport;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.sql.DataSource;
import oracle.jdbc.pool.OracleDataSource;
#Named(value = "dateBean")
#RequestScoped
public class DateBean {
private List<Date> dateList = new ArrayList<>();
public DateBean() throws ClassNotFoundException, SQLException {
String host = "jdbc:oracle:thin:#xxx:1521:xxx";
String user = "xxx";
String pass = "xxx";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(host, user, pass);
Statement stmt = con.createStatement();
String sql = "select utilizator, tip_cerere, parametri, stare from
cereri where tip_cerere='D394' and utilizator='44192556' ";
ResultSet rs = stmt.executeQuery(sql);
String u = null;
String t = null;
String p = null;
String s = null;
String d = null;
while(rs.next()) {
u = rs.getString("utilizator");
t = rs.getString("tip_cerere");
p = rs.getString("parametri");
s = rs.getString("stare");
// d = rs.getString("creation_date");
dateList.add(new Date(u,t,p,s));
}
String host2 = "jdbc:oracle:thin:#xxx:xxx";
String user2 = "xxx";
String pass2 = "xxx";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con2 = DriverManager.getConnection(host2, user2, pass2);
Statement stmt2 = con2.createStatement();
String sql2 = "insert into SPV_RAPORT_LOG values ('serban', '123',
'parametru_test')";
stmt2.executeUpdate(sql);
} catch(SQLException se) {System.out.println(se);}
catch(Exception e) {System.out.println(e);}
}
public List<Date> getDateList() {
return dateList;
}
}
The database host and name and user and passwords are put intentionally with xxx to hide them.
I am a beginner and I do not have any idea why it doesn`t insert the test statement into the database table
I have linked up a database to my Java application using the JDBC in Netbeans.
But whenever I try to write something from a TextField to a MySQL table, it doesn't work.
I have a pre-made class to make the database connection.
Here is my database class:
package testswitch;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Maarten
*/
public class Database {
public final static String DB_DRIVER_URL = "com.mysql.jdbc.Driver";
public final static String DB_DRIVER_PREFIX = "jdbc:mysql://";
private Connection connection = null;
public Database(String dataBaseName, String serverURL, String userName, String passWord) {
try {
// verify that a proper JDBC driver has been installed and linked
if (!selectDriver(DB_DRIVER_URL)) {
return;
}
if (serverURL == null || serverURL.isEmpty()) {
serverURL = "localhost:3306";
}
// establish a connection to a named Database on a specified server
connection = DriverManager.getConnection(DB_DRIVER_PREFIX + serverURL + "/" + dataBaseName, userName, passWord);
} catch (SQLException eSQL) {
logException(eSQL);
}
}
private static boolean selectDriver(String driverName) {
// Selects proper loading of the named driver for Database connections.
// This is relevant if there are multiple drivers installed that match the JDBC type.
try {
Class.forName(driverName);
// Put all non-prefered drivers to the end, such that driver selection hits the first
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
Driver d = drivers.nextElement();
if (!d.getClass().getName().equals(driverName)) {
// move the driver to the end of the list
DriverManager.deregisterDriver(d);
DriverManager.registerDriver(d);
}
}
} catch (ClassNotFoundException | SQLException ex) {
logException(ex);
return false;
}
return true;
}
public void executeNonQuery(String query) {
try (Statement statement = connection.createStatement()) {
statement.executeUpdate(query);
} catch (SQLException eSQL) {
logException(eSQL);
}
}
public ResultSet executeQuery(String query) {
Statement statement;
try {
statement = connection.createStatement();
ResultSet result = statement.executeQuery(query);
return result;
} catch (SQLException eSQL) {
logException(eSQL);
}
return null;
}
private static void logException(Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
e.printStackTrace();
}
}
And here's my JavaFX controller.
What I want is that when the "handle" button is pressed, that the data filled in the TextField gets inserted into the database.
package testswitch;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import testswitch.Database;
/**
*
* #author Maarten
*/
public class gebruikerToevoegenController {
//TextFields
#FXML
private TextField FXVoornaam, FXTussenvoegsel, FXAchternaam, FXGebruikersnaam;
#FXML
private TextField FXWachtwoord, FXEmail, FXTelefoonnummer;
//Boolean checkbox positie
#FXML
private CheckBox ManagerPosition;
#FXML
private Button gebruikerButton;
public final String DB_NAME = "testDatabase";
public final String DB_SERVER = "localhost:3306";
public final String DB_ACCOUNT = "root";
public final String DB_PASSWORD = "root";
Database database = new Database(DB_NAME, DB_SERVER, DB_ACCOUNT, DB_PASSWORD);
public void handle(ActionEvent event) throws SQLException {
String query = "INSERT INTO testDatabase.Gebruikers (Voornaam) VALUES " + FXVoornaam.getText();
try {
database.executeQuery(query);
} catch (Exception e) {
}
}
}
Thanks in advance
The string in your SQL query doesn't seem to be properly quoted. It's best to use PreparedStatement for this scenario:
public class Database {
public PreparedStatement prepareStatement(String query) throws SQLException {
return connection.prepareStatement(query);
}
...
public void handle(ActionEvent event) throws SQLException {
String query = "INSERT INTO testDatabase.Gebruikers (Voornaam) VALUES (?);";
PreparedStatement statement = database.prepareStatement(query);
try {
statement.setString(1, FXVoornaam.getText());
statement.executeUpdate();
} catch (Exception e) {
// log info somewhere at least until it's properly tested/
// you implement a better way of handling the error
e.printStackTrace(System.err);
}
}
You have to add like this in JavaFx :
String query = "INSERT INTO testDatabase.Gebruikers (Voornaam) VALUES ('{FXVoornaam.getText()}') ";
String query = "INSERT INTO testDatabase.Gebruikers(Voornaam)
VALUES('" + FXVoornaam.getText() + "')";
I am trying to compile a program UCanAccess.java. I am getting the following exception when i run it. "java.lang.ClassNotFoundException: net.ucanaccess.jdbc.UcanaccessDriver".
I have copied all the UcanAccess jar files into the folder in which my java code is. Have made DSN. Can anybody tell me why i am getting this message.
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.*;
public class UCanAccessExample {
public static void main(String args[]){
try {
String url = "jdbc:ucanaccess://c:/UCanAccess/Personinfo.accdb";
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection con = DriverManager.getConnection(url);
Statement st = con.createStatement();
String sql = "SELECT * FROM Person";
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
String name = rs.getString("name");
String add = rs.getString("address");
String phone = rs.getString("phoneNum");
System.out.println(name + " " + add + " " + phone);
}
con.close();
} catch(Exception sqlEx){
System.out.println(sqlEx);
}
}
}
Image of folder in which my files are
You need to add UCanAccess driver in class-path.
Here are ways to do it.
java.exe -classpath E:\lib\* Main
I am trying to execute simple query using below DbQuery.java class which uses DbConnector to get a Connection from DriverManager.
note:
I have already included "mysql-connector-java-5.1.25-bin.jar" on my
classpath via: export
CLASSPATH=$CLASSPATH:/home/me/ocpjp/chapter-10/mysql-connector-java-5.1.25/mysql-connector-java-5.1.25-bin.jar
I am able to connect to mysql with "mysql -uroot -ptcial
addressBook", if it matters.
have also tried running with '-cp'
argument with no avail.
I am able to get my #3 DbConnect.java class to say "Database connection established".
Also #4 DbQueryWorking.java has no issues and provides expected output .
Can you please help me understand what is the issue here ?
1) DbConnector.java
package com.me.ocpjp.chapter10;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnector{
public static Connection connectToDb() throws SQLException{
String url = "jdbc:mysql//localhost:3306/";
String db = "addressBook";
String username = "root";
String password = "tcial";
return DriverManager.getConnection(url+db, username, password);
}
}
2) DbQuery.java
package com.me.ocpjp.chapter10;
import java.sql.Connection ;
import java.sql.Statement ;
import java.sql.ResultSet ;
import java.sql.SQLException ;
import com.me.ocpjp.chapter10.DbConnector;
public class DbQuery{
public static void main(String[] args){
try(Connection connection = DbConnector.connectToDb();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from contact")){
System.out.println("ID \tfName \tlName \temail \t\tphoneNo");
while(resultSet.next()){
System.out.println(resultSet.getInt("id") + "\t"
+ resultSet.getString("firstName") + "\t"
+ resultSet.getString("lastName") + "\t"
+ resultSet.getString("email") + "\t"
+ resultSet.getString("phoneNo") );
}
}catch(SQLException sqle){
sqle.printStackTrace();
System.exit(-1);
}
}
}
3) DbConnect.java
package com.me.ocpjp.chapter10;
import java.sql.Connection;
import java.sql.DriverManager;
public class DbConnect{
public static void main(String[] args){
String url = "jdbc:mysql://localhost:3306/";
String database = "addressBook";
String userName = "root";
String password = "tcial";
try(Connection connection = DriverManager.getConnection(url+database, userName, password)){
System.out.println("Database connection established");
}catch(Exception e){
System.out.println("Database connectioni NOT established");
e.printStackTrace();
}
}
}
4) DbQueryWorking.java
package com.me.ocpjp.chapter10;
import java.sql.Connection ;
import java.sql.Statement ;
import java.sql.ResultSet ;
import java.sql.SQLException ;
import java.sql.DriverManager;
public class DbQuery{
public static void main(String[] args){
String url = "jdbc:mysql://localhost:3306/";
String database = "addressBook";
String userName = "root";
String password = "tcial";
try(Connection connection = DriverManager.getConnection(url + database, userName, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from contact")){
System.out.println("ID \tfName \tlName \temail \t\tphoneNo");
while(resultSet.next()){
System.out.println(resultSet.getInt("id") + "\t"
+ resultSet.getString("firstName") + "\t"
+ resultSet.getString("lastName") + "\t"
+ resultSet.getString("email") + "\t"
+ resultSet.getString("phoneNo") );
}
}catch(SQLException sqle){
sqle.printStackTrace();
System.exit(-1);
}
}
}
it looks like that the URL in DbConnector.java is wrong. A colon is missing. The url must be:
jdbc:mysql://localhost:3306/
and not
jdbc:mysql//localhost:3306/
your URL is wrong, you're missing a colon in it, it should be:
String url = "jdbc:mysql://localhost:3306/";