Wrong use of Java and Mysql?

I currently have a dedicated database server which runs MySQL. On the MySQL server I have 15 tables with the InnoDB engine.
These tables all have a column called "last_sync". Whenever a tablerow is updated by a java client, the "last_sync" column is refreshed.
Other java clients will query these tables with a query that looks something like this
"Select count(*) from table where last_sync > (currenttime-5 seconds) and last_sync <= (currenttime)"
So much for the background info. To stresstest my server, and see how much queries per second he can handle,
I installed Super Smack (http://vegan.net/tony/supersmack/). Super smack is a stresstest tool which can be given 2 start-up parameters.
These parameters say how many clients/threads should connect and how many times the query should be ran. When installed it
is possible to alter the stress query by editting the "select-key.smack" file. I did so and placed a query that is equal to the above statement.
Super-smack (as well as MySQL Administrator and Innotop) tells me that it can execute 50K queries per second when I use a single connection.
When I use two connections I get roughly 88K. This is logical since my server is a dual-core machine. I run super smack on my DB server.
Now, whenever I try to stresstest my server with a java written test, I can barely get to 10k queries per second on a single connection.
The app is being runned on the DB server as well. Furthermore when I add another connection, the limit stays at 10k queries.
When monitoring the connection threads with MySQL Administrator the connection threads
are often "sleeping" while, when I run the SuperSmack test they are constantly in use.
Another detail, the connection threads also gives info what it's doing ("Executing query", "Writing to net" etc.). I occasionally see "Rollback", which is strange
since my stress query is not failing in my stress application.
To make this complete, I've uploaded my little test along with the SQL creation code to the following URL: HERE
It should work straight out of the box. Naturally the table creation query should be ran and the connection settings specified in the java file.
Basically the one thing I cannot understand is why supersmack runs a factor 5-8 faster than my java test while they are
using the exact same table and are executed on the exact same machine. This however limits out the possibility of it being a database config setting.
Im personally guessing im incorrectly using transactions or the MySQL connector/j is giving problems.
I understand this might take some effort, so i'll try to add more dukes than a regular post.
-Edit. Was under the assumption that you could add more than 10 duke points.
Thanks in advance
Edited by: killingdjef on Mar 25, 2009 6:52 AM
Edited by: killingdjef on Mar 25, 2009 10:28 AM

killingdjef wrote:
10K can be perfect, however, when I run Supersmack and see that my database server can handle 8 times more queries per second on the exact same table with the exact same query,
I'm beginning to wonder if im doing something incorrect or if i'm missing something crucial.
I have no clue whats a reasonable amount of queries per second is for a dedicated innodb server
but based on the benchmark test im thinking I can squeeze out more.
The stresstest isnt representational for a single client. Its merely a simulation how many clients could be served.
The higher the queries per second, the more clients that can be served. Im trying to find out what the limit would be.I am quite aware of what impact means in terms of client processing. That however isn't the point. The point is that you intend to serve a market of some sort and support some reasonable growth. It is pointless to try to do more than that.
If you have enough "clients" running directly against that database to generate 10k queries a second then your architecture (and thus design and implementation) is very likely flawed.
For example
1. What happens to all of those clients when the database goes down either accidently or on purpose?
2. Those clients are hitting the database direct, and I don't see how you are going to get enough clients like that without internet consumers. And you absolutely do not want to expose the database that way.
3. Conversely say you have a call center with 2000 support people, which is a huge call center. There is no way that number could generate even close to 10k a second.
4. A comparable txn business model is credit card processing and a sustained speed like that would be sufficient to handle all of the credit card transaction business in the US during the peak xmas season. With extra left over.
Not to mention that you didn't address the network problem at all. Note that the numbers I outlines above doesn't allow any bandwidth for the data to get into the server in the first place.
And inserts will take more time than queries.
But as I already said, if you are using transaction then that will have an impact. Connections/threads will as well.

Similar Messages

  • Few question about Java and MySQL connection

    Hi!
    I have some problems with creating connection between Java and MySQL.
    I followed the restrictions in mysql-connector-java.jar' readme, I set the CLASSPATH :
    CLASSPATH=.;D:/mysql/mysql-connector-java.jar;
    I copied this jar file to the right place (descripted above), and I used the right steps to load it:
    Class.forName('com.mysql.jdbc.Driver"); and it throws a ClassNotFoundException
    Why? All the paths are correct, everything is on the right place.... I dont know why.
    When I installed the JBuilder8, and copied the jar file to JBuilder8/jdk4/jre/lib/ext it worked without any CLASSPATH in enviromental variables.
    If I want to run my program on machines where are not JBuilder, what should I do?
    Please help, if you can.
    Thanks,
    henpanta

    Yeah. So if I compiled my program with JBuilder to an .exe file, I cant run it on other machines, if the jar file isnt in the same place?
    If I tried your advice, java -classpath mymainclass I got the next message:
    main class not found. Believe me, its there. :(

  • The performance of management system with Java and MySQL

    Hi all,
    I want to develop one management application with Java and MySQL. However I am not sure which is a good way to design the system. The system has to deal with customers' data in the database.
    Should I create objects for every customers when application starts so that I do not need to access to the database often? Or
    Should I access to the database everytime the user want to deal with customer's data?
    Welcome for any suggestion.
    Thank you
    Pat

    Hi
    i i think u should go through MVC model or use connection pooling

  • Examination system using JSP/SErvlet and MySQL

    Hi
    I am new to JSP /servlet.
    I am designing online examination system using JSP/Servlet and MySQL ,where multiple choice questions would be selected randomly from the database. After completion of the examination user gets the results ,also the results would be stored in the database for the future reference.
    Can anyone guide me for this? If possible give me the code for similar type of application.
    Thanks

    Sounds like you want someone else to do your homework for you, did you not read this:
    "This forum works so much better when you try to program the code yourself, then let us know where it doesn't work. Otherwise you learn very little, and we work a whole lot."
    and this
    "If you want free code, have you tried searching Google for it? You may want to consider looking for survey software. It will give you the question/answer capabilities then all you have to do is find a way to grade the survey (if you will)...
    If you are using Tomcat as your server, which you probably are, there is a jdbc tutorial included in the documentation, that is the fastest way to set up your database.
    As for your random selection, have a look at Math.random(), this is one way to generate random numbers, you will need an algorithm to convert this value (between 0.0 and 1.0) into a form that can be used to select information from your database.

  • How to handle blob data with java and mysql and hibernate

    Dear all,
    I am using java 1.6 and mysql 5.5 and hibernate 3.0 . Some time i use blob data type . Earlier my project's data base was oracle 10g but now i am converting it to Mysql and now i am facing problem to save and fetch blob data to mysql database . Can anybody give me the source code for blob handling with java+Mysql+Hibernate
    now my code is :--
    ==================================================
    *.hbm.xml :--
    <property name="image" column="IMAGE" type="com.shrisure.server.usertype.BinaryBlobType" insert="true" update="true" lazy="false"/>
    ===================================================
    *.java :--
    package com.shrisure.server.usertype;
    import java.io.OutputStream;
    import java.io.Serializable;
    import java.sql.Blob;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Types;
    import javax.naming.InitialContext;
    import javax.sql.DataSource;
    import oracle.sql.BLOB;
    import org.hibernate.HibernateException;
    import org.hibernate.usertype.UserType;
    import org.jboss.resource.adapter.jdbc.WrappedConnection;
    import com.google.gwt.user.client.rpc.IsSerializable;
    public class BinaryBlobType implements UserType, java.io.Serializable, IsSerializable {
    private static final long serialVersionUID = 1111222233331231L;
    public int[] sqlTypes() {
    return new int[] { Types.BLOB };
    public Class returnedClass() {
    return byte[].class;
    public boolean equals(Object x, Object y) {
    return (x == y) || (x != null && y != null && java.util.Arrays.equals((byte[]) x, (byte[]) y));
    public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
    BLOB tempBlob = null;
    WrappedConnection wc = null;
    try {
    if (value != null) {
    Connection oracleConnection = st.getConnection();
    if (oracleConnection instanceof oracle.jdbc.driver.OracleConnection) {
    tempBlob = BLOB.createTemporary(oracleConnection, true, BLOB.DURATION_SESSION);
    if (oracleConnection instanceof org.jboss.resource.adapter.jdbc.WrappedConnection) {
    InitialContext ctx = new InitialContext();
    DataSource dataSource = (DataSource) ctx.lookup("java:/DefaultDS");
    Connection dsConn = dataSource.getConnection();
    wc = (WrappedConnection) dsConn;
    // with getUnderlying connection method , cast it to Oracle
    // Connection
    oracleConnection = wc.getUnderlyingConnection();
    tempBlob = BLOB.createTemporary(oracleConnection, true, BLOB.DURATION_SESSION);
    tempBlob.open(BLOB.MODE_READWRITE);
    OutputStream tempBlobWriter = tempBlob.getBinaryOutputStream();// setBinaryStream(1);
    tempBlobWriter.write((byte[]) value);
    tempBlobWriter.flush();
    tempBlobWriter.close();
    tempBlob.close();
    st.setBlob(index, tempBlob);
    } else {
    st.setBlob(index, BLOB.empty_lob());
    } catch (Exception exp) {
    if (tempBlob != null) {
    tempBlob.freeTemporary();
    exp.printStackTrace();
    st.setBlob(index, BLOB.empty_lob());
    // throw new RuntimeException();
    } finally {
    if (wc != null) {
    wc.close();
    public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
    final Blob blob = rs.getBlob(names[0]);
    return blob != null ? blob.getBytes(1, (int) blob.length()) : null;
    public Object deepCopy(Object value) {
    if (value == null)
    return null;
    byte[] bytes = (byte[]) value;
    byte[] result = new byte[bytes.length];
    System.arraycopy(bytes, 0, result, 0, bytes.length);
    return result;
    public boolean isMutable() {
    return true;
    public Object assemble(Serializable arg0, Object arg1) throws HibernateException {
    return assemble(arg0, arg1);
    public Serializable disassemble(Object arg0) throws HibernateException {
    return disassemble(arg0);
    public int hashCode(Object arg0) throws HibernateException {
    return hashCode();
    public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException {
    return replace(arg0, arg1, arg2);
    =================================================================
    can anyone give me the source code for this BinaryBlobType.java according to mysql blob handling ..

    Moderator action: crosspost deleted.

  • JNI communiction using a Java and a C++ Thread

    Hi,
    My purpose is to run a Java and a C++ thread parallel.
    The C++ thread receives events from a hardware. Getting an event it should put this (for testing it is just a String ) to a Java method (there the events will be collected in a vector).
    The Java thread should compute these vector step by step when it is scheduled.
    Therefore I have a Java Thread that invokes a native method.
    This C++ method
    1. stores a refernece to the JavaVM in a global var (using env->getJavaVM ),
    2. stores the object (given by JNICall) in a global var (reference to the calling java object),
    3. creates an object dynamically (this implements a Runnable C++ Interface needed for my Thread structure)
    4. and creates (dynamically) and starts a C++ Thread ( that uses the Win API ) giving it the former created object as parameter.
    Following the C++ thread uses the former stored global JavaVM to get a JNIEnv. It also uses the global stored object.
    After this I prepare for executing a callback to Java, e.g. AttachCurrentThread, GetObjectClass, GetMethodID and so on. Finally I sucessfully start some callbacks to Java (in the while loop of the thread).
    Now here is my Problem:
    The described way only works for a few calls and then raises an error. "java.exe hat ein Problem festgestellt und muss beendet werden." (german os) (In english it should be: "java.exe has detected a problem and has to be determined").
    What is wrong with my idea. It is something with the scope of my dynammically created objects? If have no idea anymore.
    Here the source code (C++ part):
    #include <jni.h>
    #include "benchmark.h"
    #include "bench.h"
    #include "canMessage.h"
    JavaVM *jvm;
    jobject javaObject;
    JNIEXPORT void JNICALL Java_Benchmark_startBench(JNIEnv *env, jobject obj, jobject obj2){
         env->GetJavaVM(&jvm);
         javaObject = obj2;
         cout << "\n C++ Starting benchmark\n\n";
         Benchmark *bm = new Benchmark();
         Thread *thread = new Thread(bm);
         thread->start();
         //thread->join(); //uncomment this there will be no error but also
                                         // no java thread doing it's job
    Benchmark::Benchmark(): _continue(false) {
    Benchmark::~Benchmark(){
    unsigned long Benchmark::run(){
         _continue = true;
         JNIEnv *jniEnv;
            jvm->AttachCurrentThread((void **)&jniEnv, NULL);
            jclass javaClass = jniEnv->GetObjectClass(javaObject);
         if(javaClass == NULL){
              cout << "--> Error: javaClass is null";
         jmethodID methodId = jniEnv->GetMethodID(javaClass, "addMessage", "(Ljava/lang/String;)V");
         if(methodId == NULL){
              cout << "--> Error: methodId is null";
         string str ("This is a test text.");
         const char *cStr = str.c_str();
         jstring javaString = jniEnv->NewStringUTF(cStr);
         jniEnv->CallVoidMethod(javaObject, methodId, javaString );
         int i_loopCount = 0;
         while(_continue){
              i_loopCount++;
              cout << i_loopCount << " C++ runing\n";
              jniEnv->MonitorEnter(javaObject);
              jniEnv->CallVoidMethod(javaObject, methodId, javaString );
              jniEnv->MonitorExit(javaObject);
              canMessage = new CANMessage();
              delete canMessage;
              canMessage = NULL;
         return 0;
    void Benchmark::stop(){
         _continue = false;
    }Is there a better and more elegant way to solve my problem?
    Thanks!

    At
    http://codeproject.com/cpp/OOJNIUse.asp
    http://www.simtel.net/product.php[id]93174[sekid]0[SiteID]simtel.net
    http://www.simtel.net/product.php[id]94368[sekid]0[SiteID]simtel.net
    you will find examples how to implement Java Interface in JNI C++ without Java coding.
    At
    http://www.simtel.net/product.php[id]95126[sekid]0[SiteID]simtel.net
    you can get pure JNI interface for DOTNET.

  • Problems with query on a DB using NetBeans Tomcat and MySql

    hi,
    I've wrote a servlet that receive uername and password from a jsp. By quering to the db the servlet verify if that user is present on the db. I've notice no errors, hovever the page displayed is the same even if the user is present on db or isn't present. Here is the class, the context.xml and the web.xml
    import java.sql.*;
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class Main extends HttpServlet
    public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    String driver = "com.mysql.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/esempio3";
    int num = 0;
    String jspPage = "";
    String user, pass;
    user = request.getParameter("username");
    pass = request.getParameter("password");
    try
    Class.forName(driver).newInstance();
    Connection connessione = DriverManager.getConnection(url,"root", "admin");
    if(connessione == null)
    throw new SQLException();
    Statement statement = connessione.createStatement();
    String SQL = "SELECT ID As num FROM Utenti WHERE Username='"+user+"' AND Password='"+pass+"'";
    ResultSet risultato = statement.executeQuery(SQL);
    num = risultato.getInt("num");
    connessione.close();
    catch(Exception e)
    jspPage = "/error.jsp";
    if ( num > 0 )
    jspPage = "/Welcome.jsp";
    else
    jspPage = "/NoFound.jsp";
    request.getRequestDispatcher( jspPage ).forward(request,response);
    THE WEB.XML FILE:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <description>bla bla</description>
    <display-name>esempiooo</display-name>
    <servlet>
    <servlet-name>Main</servlet-name>
    <servlet-class>Main</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>Main</servlet-name>
    <url-pattern>/Main</url-pattern>
    </servlet-mapping>
    <session-config>
    <session-timeout>
    30
    </session-timeout>
    </session-config>
    <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    <resource-ref>
    <description>jdbc:mysql://localhost:3306/esempio3</description>
    <res-ref-name>jdbc/Esempio3</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    </resource-ref>
    </web-app>
    THE CONTEXT.XML FILE
    <?xml version="1.0" encoding="UTF-8"?>
    <Context path="/Esempio3">
    <Resource name="jdbc/Esempio3" auth="Container" type="javax.sql.DataSource"
    maxActive="100" maxIdle="30" maxWait="10000"
    username="root" password="admin" driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/esempio3"/>
    </Context>
    Could someone help me?
    thanks

    Hi,
    the SQL string formed in that way complile, but the string in the way you said does't compile. I tryed to use PreparedStatement without succes. The result is the same. Here is the code:
    String SQL = "select ID from Utenti where USERNAME=? and PASSWORD=?";
    PreparedStatement pre = connessione.prepareStatement(SQL);
    pre.setString(1, user);
    pre.setString(2, pass);
    ResultSet risultato = pre.executeQuery(SQL);
    Thank you very much for your help

  • Problems with java and mysql error: 1064

    Hello,
    I have been struggling with the following java code for a day. I ALWAYS get the following error code : 1064 and I just can't figure out why. I am trying to insert data into a mysql table.
    Can anyone please help?
    Thanks in advance,
    Julien.
    package com.newedgegroup.pnr.misc;
    import java.sql.BatchUpdateException;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    * @author Julien Martin
    public class RunDataCopy {
        public static void main(String[] args) throws ClassNotFoundException, Exception , ParseException {
            Class.forName("com.ibm.as400.access.AS400JDBCDriver");
            String url_source = "jdbc:as400://as400a.calyonfinancial.com";
            Connection con_source = DriverManager.getConnection(url_source, "upload", "upload");
            Class.forName("com.mysql.jdbc.Driver");
            String url_target = "jdbc:mysql://localhost:3306/pnr";
            Connection con_target = DriverManager.getConnection(url_target, "root", "");
            Statement stat_source = con_source.createStatement();
    //        ResultSet rs_source = stat_source.executeQuery("select * from QS36F.GMIST4F1 po");
            String query = "SELECT " +
                    " sum (po.PGROSS) AS OPTION_PREMIUM, " +
                    "po.PFIRM, " +
                    "po.POFFIC, " +
                    "po.PACCT, " +
                    "po.PTDATE, " +
                    "po.PRR, " +
                    "po.PEXCH, " +
                    "po.PSUBEX, " +
                    "po.PFC, " +
                    "po.PSYMBL, " +
                    "po.PCLASS, " +
                    "po.PSUBCL, " +
                    "po.PSUBTY, " +
                    "po.PSDSC1, " +
                    "po.PCTYM, " +
                    "po.PSTRIK, " +
                    "po.PCLOSE, " +
                    "po.PUNDCP, " +
                    "po.PCURSY, " +
                    "po.PEXPDT, " +
                    "po.PLTDAT, " +
                    "po.PMULTF, " +
                    "po.PPTYPE, " +
                    "po.PBS " +
                    "FROM QS36F.GMIST4F1 as po " +
                    "WHERE " +
                    "0              = 0 " +
                    "AND po.PFIRM   = 'I' " +
                    "AND po.POFFIC  = '349' " +
                    "AND po.PRECID in ('T','B','Q') " +
                    "AND po.PSUBTY != ' ' " +
                    "AND po.PCMNT1 != ' E' " +
                    "AND po.PCMNT1 != ' A' " +
                    "GROUP BY " +
                    "po.PFIRM, " +
                    "po.POFFIC, " +
                    "po.PACCT, " +
                    "po.PTDATE," +
                    "po.PRR, " +
                    "po.PEXCH, " +
                    "po.PSUBEX," +
                    "po.PFC, " +
                    "po.PSYMBL, " +
                    "po.PCLASS, " +
                    "po.PSUBCL, " +
                    "po.PSUBTY, " +
                    "po.PSDSC1, " +
                    "po.PCTYM, " +
                    "po.PSTRIK, " +
                    "po.PCLOSE, " +
                    "po.PUNDCP, " +
                    "po.PCURSY, " +
                    "po.PEXPDT, " +
                    "po.PLTDAT, " +
                    "po.PMULTF, " +
                    "po.PPTYPE, " +
                    "po.PBS ";
            // System.out.println(query);
            ResultSet rss = stat_source.executeQuery(query);
            StringBuffer sb = new StringBuffer("");
            SimpleDateFormat df_s = new SimpleDateFormat("yyyyMMdd");
            SimpleDateFormat df_t = new SimpleDateFormat("yyyy-MM-dd");
            con_target.setAutoCommit(false);
            Statement stat_target = con_target.createStatement();
            int i = 0;
            try {
                while (rss.next()) {
                    i++;
                    sb.append("INSERT INTO `pnr`.`pnr_transaction` (").append("\n");
                    sb.append("`FIRM_ID`,").append("\n");
                    sb.append("`OFFICE_NUMBER`,").append("\n");
                    sb.append("`ACCOUNT_NUMBER`,").append("\n");
                    sb.append("`SALESMAN`,").append("\n");
                    sb.append("`EXCHANGE_CODE`,").append("\n");
                    sb.append("`SUBEXCHANGE`,").append("\n");
                    sb.append("`FUTURES_CODE`,").append("\n");
                    sb.append("`SYMBOL`,").append("\n");
                    sb.append("`ACCOUNT_CLASS_CODE`,").append("\n");
                    sb.append("`SUB_CLASS_CODE`,").append("\n");
                    sb.append("`SECURITY_SUB_TYPE`,").append("\n");
                    sb.append("`SECURITY_DESCRIPTION_LINE`,").append("\n");
                    sb.append("`CONTRACT_YR_MON`,").append("\n");
                    sb.append("`STRIKE_PRICE`,").append("\n");
                    sb.append("`CLOSING_MARKET_SETTLEMENT_PRICE`,").append("\n");
                    sb.append("`UNDERLYING_CLOSE_PRICE`,").append("\n");
                    sb.append("`PRODUCT_CURRENCY_SYMBOL`,").append("\n");
                    sb.append("`EXPIRATION_DATE`,").append("\n");
                    sb.append("`LAST_TRADING_DATE`,").append("\n");
                    sb.append("`MULTIPLICATION_FACTOR`,").append("\n");
                    sb.append("`PRODUCT_TYPE_CODE`,").append("\n");
                    sb.append("`CATEGORY_ID`,").append("\n");
                    sb.append("`MARKET_TYPE_ID`,").append("\n");
                    sb.append("`TAX_STATUS_ID`,").append("\n");
                    sb.append("`AMOUNT`").append("\n");
                    sb.append(") VALUES (").append("\n");
                    sb.append("'").append(rss.getString("PFIRM")).append("'").append(",").append("\n");
                    sb.append("'").append(rss.getString("POFFIC")).append("'").append(",").append("\n");
                    sb.append("'").append(rss.getString("PACCT")).append("'").append(",").append("\n");
                    sb.append("'").append(rss.getString("PRR")).append("'").append(",").append("\n");
                    sb.append("'").append(rss.getString("PEXCH")).append("'").append(",").append("\n");
                    sb.append("'").append(rss.getString("PSUBEX")).append("'").append(",").append("\n");
                    sb.append("'").append(rss.getString("PFC")).append("'").append(",").append("\n");
                    sb.append("'").append(rss.getString("PSYMBL")).append("'").append(",").append("\n");
                    sb.append("'").append(rss.getString("PCLASS")).append("'").append(",").append("\n");
                    sb.append("'").append(rss.getString("PSUBCL")).append("'").append(",").append("\n");
                    sb.append("'").append(rss.getString("PSUBTY")).append("'").append(",").append("\n");
                    sb.append("'").append(rss.getString("PSDSC1")).append("'").append(",").append("\n");
                    sb.append("'").append(rss.getString("PCTYM")).append("'").append(",").append("\n");
                    sb.append(rss.getString("PSTRIK")).append(",").append("\n");
                    sb.append(rss.getString("PCLOSE")).append(",").append("\n");
                    sb.append(rss.getString("PUNDCP")).append(",").append("\n");
                    sb.append("'").append(rss.getString("PCURSY")).append("'").append(",").append("\n");
                    sb.append("'").append(df_t.format(df_s.parse(rss.getString("PEXPDT")))).append("'").append(",").append("\n");
                    sb.append("'").append(df_t.format(df_s.parse(rss.getString("PLTDAT")))).append("'").append(",").append("\n");
                    sb.append(rss.getString("PMULTF")).append(",").append("\n");
                    sb.append("'").append(rss.getString("PPTYPE")).append("'").append(",").append("\n");
                    //sb.append(rss.getString("PBS")).append(",");
                    sb.append("1").append(",").append("\n");
                    sb.append("1").append(",").append("\n");
                    sb.append("1").append(",").append("\n");
                    sb.append(rss.getString("OPTION_PREMIUM")).append("").append("\n");
                    // sb.append(df_t.format(df_s.parse(rss.getString("PTDATE")))).append(",");
                    sb.append(") ").append("\n");
                    System.out.println(sb.toString());
                    //     stat_target.executeUpdate(sb.toString());
                    stat_target.addBatch(sb.toString());
    //        stat_target.executeUpdate(sb.toString());
                    if (i == 2) {
                        break;
                stat_target.executeBatch();
                con_target.commit();
            } catch (BatchUpdateException be) {
                System.out.println("be: "+be.getErrorCode());
                System.out.println("be: "+be.getMessage());
                be.printStackTrace();
                System.out.println("be: "+i);
            } catch (SQLException se) {
                System.out.println("se: "+se.getErrorCode());
                System.out.println("se: "+i);
    }

    What is the error message?
    I advice you to use prepared statement for batch inserting.

  • [JAVA] problems with java and mysql

    Hi, i have already installed php + mysql and work's them fine, but i want to install java + mysql. I have downloaded eclipse and installed its, that's ok. I have download tomcat and, that's ok. I have download module jconnector and have copied the file .jar in the java home and set classpath. Run and compiled this source that's ok. At runtime the program ask: Impossible connection at the database, why ? It's the source of program:
    [JAVA]
    import java.sql.*;
    public class connessione {
    private String nomeDB; // Nome del Database a cui connettersi
    private String nomeUtente; // Nome utente utilizzato per la connessione al Database
    private String pwdUtente; // Password usata per la connessione al Database
    private String errore; // Raccoglie informazioni riguardo l'ultima eccezione sollevata
    private Connection db; // La connessione col Database
    private boolean connesso; // Flag che indica se la connessione � attiva o meno
    public connessione(String nomeDB) { this(nomeDB, "", ""); }
    public connessione(String nomeDB, String nomeUtente, String pwdUtente) {
    this.nomeDB = nomeDB;
    this.nomeUtente = nomeUtente;
    this.pwdUtente = pwdUtente;
    connesso = false;
    errore = "";
    // Apre la connessione con il Database
    public boolean connetti() {
    connesso = false;
    try {
    // Carico il driver JDBC per la connessione con il database MySQL
    Class.forName("com.mysql.jdbc.Driver");
    // Controllo che il nome del Database non sia nulla
    if (!nomeDB.equals("")) {
    // Controllo se il nome utente va usato o meno per la connessione
    if (nomeUtente.equals("")) {
    // La connessione non richiede nome utente e password
    db = DriverManager.getConnection("jdbc:mysql://localhost/" + nomeDB);
    } else {
    // La connessione richiede nome utente, controllo se necessita anche della password
    if (pwdUtente.equals("")) {
    // La connessione non necessita di password
    db = DriverManager.getConnection("jdbc:mysql://localhost/" + nomeDB + "?user=" + nomeUtente);
    } else {
    // La connessione necessita della password
    db = DriverManager.getConnection("jdbc:mysql://localhost/" + nomeDB + "?user=" + nomeUtente + "&password=" + pwdUtente);
    // La connessione � avvenuta con successo
    connesso = true;
    } else {
    System.out.println("Manca il nome del database!!");
    System.out.println("Scrivere il nome del database da utilizzare all'interno del file \"config.xml\"");
    System.exit(0);
    } catch (Exception e) { errore = e.getMessage(); }
    return connesso;
    public static void main(String [] args) {
    connessione a=new connessione("asta","root","");
    if(a.connetti())
    System.out.println("Connessione al database riuscita");
    else
    System.out.println("Connessione al database non riuscita");
    [JAVA]

    With this line I always pass the username and password also:
    db = DriverManager.getConnection("jdbc:mysql://localhost/" + nomeDB);
    db = DriverManager.getConnection("jdbc:mysql://localhost/" + nomeDB, useName, Password);
    Make sure you create your users in MySQL with the correct permissions

  • Record Set Variables used in PHP and MYSQL model

    PHP MYSQL server model.
    I'e been using dreamweaver for ages and have allways admired
    how well they have kept compatibility between versions. The recent
    8.02 release was a little bit of a shock when I had to start
    rewriting all my PHP MYSQL recordset queries!
    In the bulk of my SQL queries I detect on of two states for a
    query parameter and in some queries the parameters are used more
    then once. By creating a single variable in for the recordset I've
    allways been able to check and recheck the single variable in the
    query using the standard recordset. Now in version 8.02 I am
    getting the error: Missing type for variable:colname
    So where:
    SELECT *
    FROM links
    WHERE LinkID = colname or colname=-1
    ORDER BY `Level` DESC
    used to work it does not work any more!
    I'm being forced to rewrite the query:
    SELECT *
    FROM links
    WHERE colname in (-1,LinkID)
    ORDER BY `Level` DESC
    Simple enough but where the queries get more complex the more
    variables I have to define!
    This is not Cool! Can we get a bug fix for this so that I
    dont have to rewrite all my queries!
    P.S. Since when did anyone say that the Dreamweaver was SQL
    injection safe! This issue should have been resolved back in the
    Ultradev days! I guess Kudos goes to Adobe for finally trying to
    address one of the biggest glaring issues dreamweaver has had since
    it's inception. I was allways kinda upset that I was forced to pass
    variables as text to sprintf when I knew they where numbers!
    If I Look at the resultant code now I'm sure the result
    sprintf will still be using %s instead of optionally specifying one
    of the many diferent types (
    % - a literal percent character. No argument is required.
    b - the argument is treated as an integer, and presented as a
    binary number.
    c - the argument is treated as an integer, and presented as
    the character with that ASCII value.
    d - the argument is treated as an integer, and presented as a
    (signed) decimal number.
    e - the argument is treated as scientific notation (e.g.
    1.2e+2).
    u - the argument is treated as an integer, and presented as
    an unsigned decimal number.
    f - the argument is treated as a float, and presented as a
    floating-point number (locale aware).
    F - the argument is treated as a float, and presented as a
    floating-point number (non-locale aware). Available since PHP
    4.3.10 and PHP 5.0.3.
    o - the argument is treated as an integer, and presented as
    an octal number.
    s - the argument is treated as and presented as a string.
    x - the argument is treated as an integer and presented as a
    hexadecimal number (with lowercase letters).
    X - the argument is treated as an integer and presented as a
    hexadecimal number (with uppercase letters).
    This would further protect a query from being SQL Injected!
    I'd hope that Adobe would enable a Site specfic setting or
    something that would change the behaviour to match the passed
    parameter to sprintf with the specified variable type (I'd guess
    best practice to be Numeric be type f Text be type s and Date as
    type s as well)

    Start by saying bump.
    I've still no word from Adobe if they are doing anything with
    this problem. Any one had any replys from Adobe on it? Any one
    found a work around with recoding queries?

  • JAVA and MYSQL NOW() Function only displays year?

    I have run into something interesting with running the MYSQL NOW() function.
    Here is what I'm running:
    SELECT  NOW() from databaseThis gives me "2010" only. Any idea why this may be? If I run the same mysql query in mysql from the command line I get the correct output "2010-01-14 14:10:03".
    Has anyone else seen this behavior?
    Edited by: crusherdestroyer on Jan 14, 2010 12:19 PM

    I'm not doubting that. Here is how I'm using it.
    import java.util.Date;
    String userName = "username";
                   String password = "password";
                   String url = "jdbc:mysql://localhost/database";
                   Class.forName ("com.mysql.jdbc.Driver").newInstance ();
                   conn = DriverManager.getConnection (url, userName, password);
                   //System.out.println ("Database connection established");
                   Statement s = conn.createStatement ();
                   s.executeQuery ("SELECT NOW() from database' ");
                   ResultSet rs = s.getResultSet ();
                   int count = 0;
                   Date timenow = null;
                   while (rs.next ())
                       timenow = rs.getDate ("NOW()");
                    ++count;
    System.out.println (timenow);Tried this too.
    String userName = "username";
                   String password = "password";
                   String url = "jdbc:mysql://localhost/database";
                   Class.forName ("com.mysql.jdbc.Driver").newInstance ();
                   conn = DriverManager.getConnection (url, userName, password);
                   //System.out.println ("Database connection established");
                   Statement s = conn.createStatement ();
                   s.executeQuery ("SELECT NOW() from database' ");
                   ResultSet rs = s.getResultSet ();
                   Date timenow = null;
                       timenow = rs.getDate ("NOW()");
    System.out.println (timenow);Edited by: crusherdestroyer on Jan 14, 2010 2:04 PM
    Edited by: crusherdestroyer on Jan 14, 2010 2:07 PM

  • Steps cor connectivity java and mysql

    Hi can any one list the steps for the connectivity of java & mysql.
    jdk1.6 & mysql5

    1) Learn JDBC: http://java.sun.com/docs/books/tutorial/jdbc/index.html
    2) Obtain the MySQL JDBC driver: http://www.mysql.com/products/connector/j/
    3) Read the MySQL JDBC driver reference documentation: http://dev.mysql.com/doc/refman/6.0/en/connector-j-reference.html

  • Anyone Update Date/Timestamp using CachedRowSets, Java and Oracle 10g

    How to do this...
    a very small, direct snippet of code would be great..
    or direct me to a CURRENT document.
    Thanks

    What will I get back from Oracle with TO_CHAR?
    I am using a quoted string and supplying parameters.
    In other words, when I do the date comparison with a TO_DATE I already know that I am getting 12:00:00 AM back and the paramter I can manipulate.
    Example:
    TO_DATE(datefield) = formattedDateParameter
    The "TO_DATE(datefield)" is part of my prepared sql statement.
    I am not sure how much manipulation of the where clause I can do.
    My querystring would look like the following.
    sql = "SELECT " + REPORTTRANSDATE + REPORTRETURNCODE + " FROM " + REPORTTABLE + " WHERE " + REPORTD + "=?" + " AND " + "TO_DATE(" + REPORTTRANSDATE + ")" + ">=?" + " AND " + "TO_DATE(" + REPORTTRANSDATE + ")" + "<=?" + " ORDER BY " + REPORTTRANSDATE;
    Thanks.

  • Using Safari & Java from Spain

    To anyone who may have knowledge of Java/Safari in Spain or Europe.
    I am currently studying abroad in Spain and i have noticed that my computer and others have been having troubles using the Java Script for Facebook, Yahoo, Pogo.com and other sources. We currently run a slightly out of date wireless network based off PCs; However, PCs are having the same issues.
    Does anyone know if Spain or Europe doesn't use Java as much. And does anyone know if Proxies are affect the use of Java and if so, where can i enter proxy information to fix the issue.
    Thank you to anyone who replies.

    I was thinking about my problem some more and i was
    wondering if you or anyone knew how to set proxies
    for Java. For example, yes, you can set proxies under
    settings/network and you can set proxies in Firefox,
    iChat, and more. Is there a way for Java?
    Java is not a protocol, it's an application framework. It communicates using protocols in your ip stack. You can set proxies for those protocols. I suspect you mean javascript, but the same applies there, except that it's all http. I don't want to get into rudimentary aspects of networking, I'm sure you can find very good references.
    What's really interesting is that you seem to be implying that there is some sort of censorship of web sites in Spain - just like in China. And that you're looking for a what's known as a circumventor. I know that there was a recent ruling in the Spanish counrts that judges could block web sites they found to be a threat to national defense. Is this perhaps what you're seeing?

  • Set a max Upload quantity dreamwaver php and mysql

    The issue,
    using dreamweaver php and mysql I Would like to set a max
    quantity limit on file upload per user. i.e max 5 uploaded images
    allowed per user.
    Here is a basic example of the creation. Just need the
    implementation of how to set a max upoad limit.
    create table authors(
    id int not null auto increment primary key,
    name varchar(10) not null
    image_quantity tinyint(1),
    create table images(
    aid int not null,
    image_filename varchar(50),
    foreign key (aid) references authors(id)
    User id 1 would upload a file into the table images from a
    php or html webpage. i.e set values "thomas.jpeg", "1"
    i want to set a max upload of 5 images per user. (a folder
    for each user id will be created and photos stored in that).
    I could add a field of max_upload tinyint(1) to the table
    users and construct a php script that could add the amount of
    images entered by a user into the images table and add a +1 to each
    added. Problem is i dont know how to create that script or mysql
    querty in order to enter into a recorset for example.
    As anyone have any ideas of the best way to set a max
    quantity limit of uploads.
    Thank you.

    The issue,
    using dreamweaver php and mysql I Would like to set a max
    quantity limit on file upload per user. i.e max 5 uploaded images
    allowed per user.
    Here is a basic example of the creation. Just need the
    implementation of how to set a max upoad limit.
    create table authors(
    id int not null auto increment primary key,
    name varchar(10) not null
    image_quantity tinyint(1),
    create table images(
    aid int not null,
    image_filename varchar(50),
    foreign key (aid) references authors(id)
    User id 1 would upload a file into the table images from a
    php or html webpage. i.e set values "thomas.jpeg", "1"
    i want to set a max upload of 5 images per user. (a folder
    for each user id will be created and photos stored in that).
    I could add a field of max_upload tinyint(1) to the table
    users and construct a php script that could add the amount of
    images entered by a user into the images table and add a +1 to each
    added. Problem is i dont know how to create that script or mysql
    querty in order to enter into a recorset for example.
    As anyone have any ideas of the best way to set a max
    quantity limit of uploads.
    Thank you.

Maybe you are looking for

  • Can't Login to my User Account

    First of all I apologise for posting this question in two forums but as my problem persists I think it's an account issue, rather than hardware. My problem started after the Mac "froze" after I had rebooted it. After a few minutes all I had was the s

  • Canon ZR40 camcorder and a Macbook with the latest OS.

    I have a Canon ZR40 and a Macbook with the latest OS.  My iMovie does not recognize the camcorder.  Can someone please give me step by step directions on what I should be doing?

  • Running Solaris9 built C++ program on Solaris 10

    Hello, I have an executable that builts and runs fine on Solaris 9. Once copied to a Solaris 10 machine, it is not recognized as an executable. On Solairs 9 machine: $ uname -a SunOS sunqas2 5.9 Generic_117171-07 sun4u sparc SUNW,Sun-Fire-280R $ file

  • How do I burn a DVD on my mac air and be able to loop it in a dvd player

    What program can I use on my mac air to burn a dvd that I will be able to loop on a dvd player

  • Dc integration between solaris 10 & windows 2k3 server

    Dear All I have a sun solaris server & a windows 2003 server where we configure ADC.win 2K3 is my Domain Controller. i wan't a solution that whenever i create a user on my DC same user should created in solaris . is it possible or any one guide me fo