insert cmr values into database - java

I have a CMR file with different values, but I don't know how to use the separator.
I want to store "numberPacketsLost", "jitter", and "latency" into a mySQL database using java netbeans with button.
Thanks! :)
Code from cmr file :
"cdrRecordType","globalCallID_callManagerId","globalCallID_callId","nodeId","directoryNum","callIdentifier","dateTimeStamp","numberPacketsSent","numberOctetsSent","numberPacketsReceived","numberOctetsReceived","numberPacketsLost","jitter","latency","pkid","directoryNumPartition","globalCallId_ClusterID","deviceName","varVQMetrics"
INTEGER,INTEGER,INTEGER,INTEGER,VARCHAR(50),INTEGER,INTEGER,INTEGER,INTEGER,INTEGER,INTEGER,INTEGER,INTEGER,INTEGER,UNIQUEIDENTIFIER,VARCHAR(50),VARCHAR(50),VARCHAR(129),VARCHAR(600)
2,2,1732470,2,"4241",47660016,1319556369,192,33024,191,32852,0,0,0,"8ea4f719-c49c-4456-a2a8-972ebcfb57a9","2b494acb-9359-7f52-b0ef-7b66bb672b73","StandAloneCluster","SEP0026CB3C2A16","MLQK=0.0000;MLQKav=0.0000;MLQKmn=0.0000;MLQKmx=0.0000;ICR=0.0000;CCR=0.0000;ICRmx=0.0000;CS=0;SCS=0;MLQKvr=0.95"
2,2,1732447,2,"5352",47659963,1319556371,1409,242348,1408,242176,0,0,0,"61ca6d9f-8e75-4282-b303-3fea2fa75df7","2b494acb-9359-7f52-b0ef-7b66bb672b73","StandAloneCluster","SEP64168D506D26","MLQK=4.5000;MLQKav=4.3554;MLQKmn=4.1440;MLQKmx=4.5000;ICR=0.0000;CCR=0.0029;ICRmx=0.0263;CS=1;SCS=1;MLQKvr=0.95"
2,2,1732134,2,"5502",47658367,1319556373,28529,4906988,28537,4908364,0,0,0,"d1717925-89bf-41b4-b122-6162db89128f","2b494acb-9359-7f52-b0ef-7b66bb672b73","StandAloneCluster","SEP64168D50A4DB","MLQK=4.5000;MLQKav=4.4570;MLQKmn=4.1440;MLQKmx=4.5000;MLQKvr=0.95;CCR=0.0011;ICR=0.0000;ICRmx=0.0267;CS=9;SCS=9"

You need to open up the cmr file, read through it line by line skipping the headers and extract the data. Once you get the needed data, just write a query to insert into the database.
BufferedReader br = new BufferedReader(new FileReader(new File("myCmrFile")));
String line = null;
int linecount = 0;
while ((line = br.readLine()) != null){
if (linecount++ < 2) // skip the headers
continue;
// split the data and convert to integers
String[] data = line.split(",");
Integer packetsLost = Integer.valueOf(data[10]);
Integer jitter = Integer.valueOf(data[11]);
Integer latency = Integer.valueOf(data[12]);
// now insert into the db, query will look something like this
String query = "INSERT INTO myTable (numberPacketsLost, jitter, latency) VALUES(?,?,?)";
PreparedStatement ps = connection.prepareStatment(query);
ps.setInt(1, packetsLost);
ps.setInt(2, jitter);
ps.setInt(3, latency);
ps.executeUpdate();
}
This code won't work exactly, you will need to change it around based on the real values of your database.

Related

UCAExc:::3.0.7 unexpected token: logDate

Good day, all. I am working on a personal project that needs to interact with an ms access 2016 db. My java application gets data from a user and this info is stored in an Object[]. I am trying to insert the elements of my obj array to a table in my db. This is my code:
Connection conn = null;
PreparedStatement pstmnt = null;
String sql = null;
ResultSetMetaData md = null;
Statement stm = null;
ResultSet rs = null;
int i = 0;
String q = "SELECT * from QueryData";
try{
conn = DriverManager.getConnection("jdbc:ucanaccess://filePath");
stm = conn.createStatement();
rs = stm.executeQuery(q);
md = rs.getMetaData();
int count = md.getColumnCount();
String[] colName = new String[count];
for (int n = 1; n <= count; n++)
colName[n-1] = md.getColumnLabel(n);
while ( i <= data.length) {//data being the object array containing the data to be inserted in db
query = "INSERT into QueryData ('"+colName[i]+"') VALUES ('"+data[i]+"')";
//The following code is where I get the exception
pstmnt = conn.prepareStatement(query);
//some more code follows..
On the first pass throught the while loop, colName[i] is "logDate" which is the first field in the table and data[i] is a LocalDate object formatted as 2016-12-23. I know I did not close the while loop above nor did I given the catch clause, but my program does not run past the pstmnt assignment. I keep getting the exception "net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::3.0.7 unexpected token: logDate".
Any assistance will be greatly appreciated as I've scoured the web amd this forum but could not find a working solution to my problem.
You are surrounding your column name with quotes, which isn't allowed. You can use square brackets instead (although not really necessary unless you have spaces in the field names, which Access allows).
query = "INSERT into QueryData (["+colName[i]+"]) VALUES ('"+data[i]+"')";
You might also need to use # instead of ' to delimit the date value. Access used to use # for date delimiters, and I'm not sure if more recent versions accept ':
query = "INSERT into QueryData (["+colName[i]+"]) VALUES (#"+data[i]+"#)";

How to a csv file in oracle using sql loader in java

I want to load data from a csv file to oracle database. Here is my code-
void importData(Connection conn) {
Statement stmt;
String query;
String filename = "C:/CSVData/Student.csv";
try {
stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
query = "LOAD DATA INFILE '" + filename + "' INTO TABLE Student FIELDS terminated by ',' ;";
System.out.println(query);
stmt.executeQuery(query);
} catch (Exception e) {
e.printStackTrace();
stmt = null;
}
}
This code runs perfectly and load data in mysql. But now I want to load data in oracle. what change do i have to make in query. Please help me. Thank you in advance...
First, you need to write a control file.
Control file example FYI:
Load data
infile "D:/Viki/test.CSV" --the input file(s) you need to import
truncate --the option you need do. (truncate, append, insert, replace. insert by default)
into table vk_recon_China_201409_i --table need insert to
fields terminated by "," --
trailing nullcols
(
col_a filler
, col_b "Trim(:col_b)"
, col_c "To_Date(:col_c,'yyyy/mm/dd hh24:mi:ss')"
, seqno sequence(Max,1)
)
Then, call sqlldr command by Runtime.exec or ProcessImpl.start,
public void startUp() {
StringBuffer sb = new StringBuffer();
String path = "sqlldr user/password#sid readsize=10485760 bindsize=10485760 rows=1000 control=controlFileName.ctl log=controlFileName.log direct=true \n pause";
try {
Process pro = Runtime.getRuntime().exec(path);
BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream()), 4096);
String line = null;
int i = 0;
while ((line = br.readLine()) != null) {
if (0 != i)
sb.append("\r\n");
i++;
sb.append(line);
}
} catch (Exception e) {
sb.append(e.getMessage());
}
}
Try making the external table.You can create an external table on your CSV file using ORACLE_LOADER driver and then update your existing table with data in your external table using DML (MERGE for example).
I think below query should work.
query = "LOAD DATA INFILE '" + filename + "' APPEND INTO TABLE Student FIELDS terminated by ',' ;";
For more info:-
http://docs.oracle.com/cd/E11882_01/server.112/e16536/ldr_control_file.htm#SUTIL005

How to save html file in MySQL DB using JDBC?

I have html file as String and I want to insert it into MySQL DB, using update query. I tried this:
Statement st = connection.createStatement();
String query = "UPDATE orders SET status='ready', html='"+html+"' WHERE id='123'";
int num = st.executeUpdate(query);
But I get following exception:
MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'zglosBladWindow').ck_window.showCenter('this');" href="#">zg?o? b??d na stronie<' at line 1
This is somwhere inside HTML - probably I cant just quote html with "" and insert it as it contains many special characters and quotes also - so how I can insert it? Should I encode it somehow?
I'd advice you to use PreparedStatement rather than Statement.
String query = "UPDATE orders SET status=?, html=? WHERE id=?";
PreparedStatement stmnt = conn.PreparedStatement(query);
stmnt.setString(1, yourtext);
....
int num = st.executeUpdate();
You should use PreparedStatement construct, as your HTML string may contain quotes or double qoutes. Read more here
You should use PreparedStatement, but I'd rather save the path in MySQL instead of saving the file.
You should probably use something like this,
StringBuilder contentBuilder = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new FileReader("mypage.html"));
String str;
while ((str = in.readLine()) != null) {
contentBuilder.append(str);
}
in.close();
} catch (IOException e) {
}
String content = contentBuilder.toString();

How to parse data from a text file which contains lots of records and each value is separated by a space/tab or maybe both

I actually need to create a database with 421 columns and I have created it. Now I have to load data into the database using a Java program. The data that I need to input into the DB is present in a text file. The values in the text file are separated by space/tab or may be both. How do I extract data from this text file so that the first value is entered under column1, second value under column 2 and so on.... 421st value under column421 and 422nd value under 1st column again and so on. I am little poor at file handling and parsing in java, so please help.
421 columns? Wow, you probably should split that huge table into a proper model with relationship. But anyway, that's off-topic.
If you really want to do it using Java, here is a possibility:
public static void readFromFile(String pathToFile) {
final BufferedReader reader = getFileReaderInClasspath(pathToFile);
try {
String line = null;
while ((line = reader.readLine()) != null) {
final StringTokenizer tokenizer = new StringTokenizer(line, "\s\t");
final List<String> columns = new ArrayList<String>();
while (tokenizer.hasMoreTokens()) {
columns.add(tokenizer.nextToken());
}
saveIntoDb(columns);
}
reader.close();
} catch (IOException e) {
throw new IllegalArgumentException("Error reading file (" + pathToFile + ")", e);
}
}
And obviously you'll need to implement the saveIntoDb(List) method, that inserts the columns into your database.
Alternatively, you could store each list of columns into a
List<List<String>>
which contains all the rows, and add all of that to the database at the end of the process only.
Why you dont do with sql statement? Below example for mysql, I showed delimiter as tab:
LOAD DATA LOCAL INFILE '/importfile.csv'
INTO TABLE test_table
FIELDS TERMINATED BY '\t'
LINES TERMINATED BY '\n'
(field1, filed2, field3);
http://dev.mysql.com/doc/refman/5.0/en/load-data.html
edit:
if delimiter is optional maybe you can read via buffered reader an analyze? I didnt check the code but you can write something like this and check text during the loop. I have replaced all tabs to space then I used delimiter as space but if your values containing space then it is problem
BufferedReader br = new BufferedReader(new FileReader("myText.txt"));
String s;
while((s=br.ReadLine)!= null){
s.replace("\t"," ");
String[] sub = s.split(" ");
String statement = "insert into myTable (clm1, clm2, clm3) Values (";
for(int i=0:i<sub.length;i++){
if((i % 420) == 0){
mySqlStatement.ExecuteQuery(statement);
statement = "insert into myTable (clm1, clm2, clm3) Values (";
}
if(i==0){
statement = statement + sub(i);
}else{
statement = statement + "," + sub(i);
}
}
statement = statement + ")";
mySqlStatement.ExecuteQuery(statement);
}

Populating database via jdbc

In the below code, values are inserted manually: 13 and Aman. But what I am doing is reading a file and then till the completion of the file, I am inserting values from it into mysql database tables.
public class Main {
public static void main(String[] argv) throws Exception {
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver);
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctutorial", "root", "root");
Statement st = con.createStatement();
int val = st.executeUpdate("INSERT employee VALUES(" + 13 + "," + "'Aman'" + ")");
System.out.println("1 row affected");
}
}
I was trying to use each line like this:
String query = "INSERT INTO home (home_no, arrival_time, duration, persons, price, origin_city) VALUES("+line+");";
How do I do it?
Depending on how large the contents of the file that you are reading, it may be worth while to check LOAD DATA INFILE syntax, rather than executing queries in a for or while loop.
Edit:
Without seeing your code and line is the current line of the file you are reading and that you are using the syntax above to store the query, I would break down your problems,
Check the line variable prior to executing the query
Check how to insert the values manually opposed to reading the contents of the file, as you had shown above with 13 and Aman.
Figure out how to piece those two together, may need string manipulation.
This should be all you need.
BufferedReader rd = new BufferedReader(new FileReader("yourFile.txt"));
String line;
while ((line = rd.readLine()) != null)
{
// This time this loop runs, you will have the next time of your file.
insertARecord(line.split(" "));
}
rd.close();
// A bit further
public void insertARecord(String[] data)
{
// insert your record.
}

Categories