i can't add Arabic numbers thru java to oracle 10g - java

I'm facing a problem with adding Arabic number to oracle 10g database. Arabic words are added successfully but if i add number in my string then numbers are saved as ?? in the database.
I thing i should fix the java code so it can add number cause if i change ?? with Arabic number in oracle SQL developer it's work fine.
Here is a example : 'قبل اكثر من ?? شهر' --> this should be like this 'قبل اكثر من ١٢ شهر'
i have change the database character set and NLS_LANG so oracle could support Arabic.
Please i need help.

this is servlet part.
String PeriodNameList=request.getParameter("PeriodNameList");
DataBaseConnection DataBaseConnection=new DataBaseConnection();
Con = DataBaseConnection.getConnection();
AgendaPeriodesBean AgendaPeriodesBean=null;
String [] SplitedPeriodNameList=PeriodNameList.split(",");
for(int j=0;j<SplitedPeriodNameList.length;j++){
AgendaPeriodesBean=new AgendaPeriodesBean();
AgendaPeriodesBean.setAGENDA_PERIODE_TRANS_NAME(SplitedPeriodNameList[j].trim());
Agenda.AddAgendaPeriodTrans(AgendaPeriodesBean);
j++;
}
DAO Part.
public Integer AddAgendaPeriodTrans(AgendaPeriodesBean Bean) throws UnsupportedEncodingException {
Integer updated = null;
PreparedStatement preparedStatement = null;
StringBuffer query = new StringBuffer();
query.append("INSERT INTO AGENDA_PERIODE_TRANSLATION ( ");
query.append(" AGENDA_PERIODE_TRANS_NAME ");
query.append(" ) ");
query.append(" VALUES (?)");
int counter = 1;
try {
preparedStatement = con.prepareStatement(new String(query));
String str = new String(Bean.getAGENDA_PERIODE_TRANS_NAME().getBytes("8859_1"), "UTF-8");
System.out.println("str : str : "+str);
if (Bean.getAGENDA_PERIODE_TRANS_NAME()!= null) {
preparedStatement.setString(counter++, Bean.getAGENDA_PERIODE_TRANS_NAME());
} else {
preparedStatement.setNull(counter++, Types.NVARCHAR);
}
updated = preparedStatement.executeUpdate();
} catch (SQLException sqlException) {
System.out.println("AddAgendaPeriodTrans : "+sqlException.getMessage());
updated=null;
} finally {
query = null;
try {
if (preparedStatement != null) {
preparedStatement.close();
}
} catch (Exception exception) {
}
}
return updated ;
}

Related

How can you get a JTextField to work in a SQLite Select statement?

I am working on a program which will when finished allow the end user to keep track of there sound packs in a database through SQLite. The newest problem I am running into is that I can not get the Select statement to take a JTextField input. The reason that I want to do this is that I already have the text fields linked through the insert method. I have tried switching the variable types in the readAllData method and I am not entirely sure what other way to fix it.
The fields are as follows
PackId
PackName
VendorName
PackValue
what I want to happen is when I hit the Update button I want the data in the database to print out to the console (for now) and I am also going to be adding a select specified records method as well.
Here is the code I do apologize in advance this is a very long project:
public void readAllData() throws SQLException {
Connection conn = DriverManager.getConnection("jdbc:sqlite:packsver3.db");
PreparedStatement ps = null;
ResultSet rs = null;
try {
String sql = "SELECT * FROM packs";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()) {
String PackId = PackId.getText();
String PackName = PackName.getText();
String VendorName = VendorName.getTextField();
String PackValue = rs.getTextField;
System.out.println("All Packs\n");
System.out.println("PackId: " +PackId);
System.out.println("PackName: " +PackName);
System.out.println("VendorName: " +VendorName);
System.out.println("PackValue: " +PackValue+"\n\n");
}
} catch (SQLException e) {
System.out.println(e.toString());
}finally {
try {
assert rs != null;
rs.close();
ps.close();
conn.close();
} catch (SQLException e) {
System.out.println(e.toString());
}
Console Output

Can't populate jtable with mysql "like" statement

I am building an application in which you can save deals to database. I'd like to search deals in my database and populate my jtable with relevant results. I want to query my database on keyrelease event. I know it is not an efficient method but I am curious why I can't get it to work.
Below is a sample code that tries to query a database table with ID and country names. There are only 3 country names that start with "D". Somehow I can get country names printed out but can't get them to populate jtable.
The error -
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException" I can't get ResultSet rs1 into a Object[][] . It works fine if I do System.out.println(rs1.getString("Name")
Below is the code -
private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {
String columnName[] = new String[] { "Name" };
Object oss[][] = new Object[3][];
ResultSet rs1 = null;
int li = 0;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
java.sql.Connection con = DriverManager.getConnection(Url, User, Password);
Statement st = con.createStatement();
String query = "SELECT * from unit.cntry WHERE Name LIKE '" + abc.getText() + "%';";
rs1 = st.executeQuery(query);
} catch (Exception e) {}
try {
while (rs1.next()) {
oss[li][0] = rs1.getString("Name");
li++;
}
myTable.setModel(new DefaultTableModel(oss, columnName));
} catch (SQLException ex) {
System.out.println(ex.toString());
} finally {
try {
if (rs1 != null) rs1.close();
} catch (SQLException e) {}
}
}
oss[li] = new Object[1];
oss[li][0] = rs1.getString("Name");
Other data structures might be more appealing.

Getting a specific cell from specific row and column out of MySQL database, jdbc, java

I'm trying to get a specifc customer id out of a MySQL table from a telephone number input from the user to use it to add a new order to that customer id. I'm trying to use a method that creates a list being filled by resultset but I keep being returned nothing, more specificly empty square brackets "[]"
This is the code im using.
if((getCustomerID.getCustomerID(inputContactNumber).toString()).equals("[]")){
JOptionPane.showMessageDialog(null, "Customer phone number does not exist.\nTry again or create new customer.");
return;
} else {
customerID = Integer.parseInt(getCustomerID.getCustomerID(inputContactNumber).toString());
insertOrder.insertOrder(customerID);
}
getCustomerID():
public List<Customer> getCustomerID(String phoneNumber) throws SQLException{
List<Customer> customerList = new ArrayList();
String selectCustomerID = "SELECT idcustomer FROM customer WHERE contactNumber = " + phoneNumber;
try {
MyConnection mc = new MyConnection();
dbConnection = mc.getConnection();
statement = dbConnection.createStatement();
ResultSet rs = statement.executeQuery(selectCustomerID);
while (rs.next()){
int customerID = rs.getInt("idcustomer");
Customer c;
c = new Customer (customerID);
customerList.add(c);
}
}
catch (SQLException e){
System.err.println(e);
return null;
}
finally{
if (statement != null){
statement.close();
}
if (dbConnection != null){
dbConnection.close();
}
}
return customerList;
}//end of getGetCustomerID()
Any input is greatly appreciated
-Edit-
MyConnection()
public class MyConnection {
public Connection connection = null;
public Connection getConnection()
{
System.out.println("---- MySql Connecting ----");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Can't find MySQl Driver.");
e.printStackTrace();
}
System.out.println("Driver Registered.");
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/quotedb","root","");
} catch (SQLException e) {
System.out.println("Connection Failed.");
}
if (connection != null) {
System.out.println("Connection Established.");
} else {
System.out.println("Connection Failed.");
}
return connection ;
}
Have you tried executing this query in a SQL Programm? As it looks like simply no result is returned, thus the empty square brackets which is the String equivalent of an empty Array.
toString() on an Array is generally a bad idea, you better use length to determine if the Array is empty. Furthermore it is not clear if the result should be unique or not:
If the function getCustomerID.getCustomerID(inputContactNumber) returns more than one result you try to parse a Int like [3453,3543] which will never be what you want. Instead you should use .get(0) on the Array to retrieve the first element.
Please change your select query to
"SELECT idcustomer FROM customer WHERE contactNumber = '"+phoneNumber+"'"
it will work fine i hope
Change the if condition to:
if(getCustomerID(inputContactNumber) == null || getCustomerID(inputContactNumber).isEmpty()){

ResultSet search Error in JDBC

so I am a beginer in JDBC - SQL Programming. I need a little advice which is most probably about SYNTAX.
So, Problem = I'm trying to search a record which has name(string provided in function argument) in the record. Following is my code. Now I've designed this code in such a way that there can be more than 1 records with the same name, so all of that records' data will be printed (by ShowData() Function).
protected static void SearchbyName (String toCompareName)
{
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
boolean flag = false; //to confirm if record has found atleast once
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT idEmployee FROM employee WHERE name = ' "+toCompareName+" ' ");
if( !(rs.next()) ) //if ResultSet is not empty
{
while(rs.next()) //reading all records with the same name, extracted by Query
{
int foundID = rs.getInt("idEmployee"); //extracting ID of found record
ShowRecord(foundID); //prints record of foundID fromDB
flag = true; //set flag
}
}
if(flag==false) //if no record found
{
JOptionPane.showMessageDialog(null, "ERROR:: No Records Found..", "Not Found", JOptionPane.ERROR_MESSAGE);
}
//close connection
if(rs!=null)
{ rs.close(); }
if(stmt!=null)
{ stmt.close(); }
if(conn!=null)
{ conn.close(); }
}
catch(SQLException e)
{ System.err.println(e); }
catch(Exception e)
{ System.err.println(e); }
}
So here it is. As far as my understanding goes, there is some problem with either RESULTSET rs or the Query I'm executing.
Kindly help. & if you can suggest a better approach for search, sure do please. I'm going to write 4 more functions SearchbyAge, SearchbyQualification, SearchbySpecialization on the same pattern.
Just this is enough
while(rs.next()) //reading all records with the same name, extracted by Query
{
int foundID = rs.getInt("idEmployee"); //extracting ID of found record
ShowRecord(foundID); //prints record of foundID fromDB
flag = true; //set flag
}
You don't have to check the data in resultset this way with a if case
if( !(rs.next()) )
This will move to the next record in the resultset
SOVLED
My error was in query. I was putting spaces in string's syntax which I was comparing.
WRONG = `"(.. WHERE name = " ' +toCompareName+ '" ");
RIGHT = `"(.. WHERE name = "'+toCompareName+'" ");
So thats it. Hope it helps to anyone else. :)

get data from flat file and insert data into database in Java

I open new question about the extract data and insert to database. I change and modified the code become like this but still not working.
Flat file:
DT|00000001|TMDWH|UNIFI|00380520160|MAH SIEW YIN|11 |JALAN PP 2/8|TAMAN PUTRA PRIMA|PUCHONG|SELANGOR|47100|MALAYSIA|801110-14-5498||||||VOBB||A||11|JALAN PP 2/8|||TAMAN PUTRA PRIMA
DT|00000002|TMDWH|UNIFI|00322012091|JUNITA BINTI JAMAL|6 10 KONDOMINIUM FAJARIA|JALAN PANTAI BARU|KUALA LUMPUR|KUALA LUMPUR|WILAYAH PERSEKUTUAN|59200|MALAYSIA|800129-09-5078||||||VOBB||A|||JALAN PANTAI BARU|6|KONDOMINIUM FAJARIA|KUALA LUMPUR
Program:
public void massageData(String tmp) {
String[] fields = tmp.replace("\"", " ")
.replace("\'","\'\'")
.trim()
.split("\\s*\\|\\s*");
Connection conn = null;
ResultSet rs = null;
PreparedStatement stmt = null;
String actualMSISDN = parseMSISDN(fields[5]);
if (actualMSISDN.length() > 8) {
String [] aNo = getAreaCode(actualMSISDN).split("\\|");
field[0] = getiCtr(parseMSISDN(fields[5]));
String stateCode = lookupStateCode(State);
String sQuery = "insert into DATA_999 ( ,RecordType,RecordNumber,SourceSystemApplicationId,TargetApplicationId,TelNo,Name,HouseNo,StreetName,AppartmentSuite,TownCity,State,PostalCode,Country,NewIC,OldIC,PassportNo,BRN,LatitudeDecimal,LongitudeDecimal,ServiceType,IndicatorType,CreateDate,Filler,Cr_Nl,HouseNo_New,LotNo_New,StreetName_New,AptNo_New,BuildingName_New,LowIDRange,HighIDRange,SectionName) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
try {
conn = ds.getConnection();
stmt = conn.prepareStatement(sQuery);
int col = 0;
for (String field : fields) {
stmt.setString(++col, field); // Note: SQL API is 1-based (not zero-based)
}
int dbStat = stmt.executeUpdate();
conn.close();
} catch (SQLException s){
logger.error(s.getMessage());
}
finally {
try {if (stmt != null) stmt.close();} catch (SQLException e) {}
try {if (conn != null) conn.close();} catch (SQLException e) {}
}
}
}
You're actually trying to insert double the amount of fields in 1 row. Also you seem to have an error in your sql query: the first field is absent and there's only a comma there.
It also seems to me that you're not doing anything yourself: you use the advice people give you, change your code and if it doesn't work you create a new question.

Categories

Resources