简体   繁体   中英

mysql connection issue in first try

I have been learning java for about 3 weeks. I wanted to connect mysql with java and I'm trying now. But there is a problem. I have already installed php,apache,mysql three in for my ubuntu. And I can reach phpmyadmin from port 80 . I think there is a problem when connecting database this is why I said port.

Here is the my table:

+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(2)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(32) | NO   |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

And here is the java code:

import java.sql.DriverManager;
import java.sql.Statement;

public class Main {

    public static void main(String args[]) {
        try {

            java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:80/test", "root", "1");

            Statement state = (Statement) conn.createStatement();
            String name = "try";
            state.executeUpdate("INSERT INTO deneme (name) VALUES (" + name + ")");

        } catch (Exception e) {
        }
    }
}

This code runs about 20 seconds and returns BUILD SUCCESSFUL (total time: 21 seconds) What is your idea about this problem?

I assume the issue is, port 80 is reserved for the web (HTTP) server, not for MySQL. The default port for MySQL is 3306.

The single quotes will fix your problem...

state.executeUpdate("INSERT INTO deneme (name) VALUES ('" + name + "')");

By using a PreparedStament you will not need to mess with single and double quote combinations.

Note that the reason why a try statement is required, is in order to report the exception, since many things may go wrong when accessing a database report the exception message and it will help you find the problem.

Also, it is always useful to check if the JDBC driver exists before trying to connect. Insert another try statement, like this one:

    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        String msg = "The com.mysql.jdbc.Driver is missing\n"
                + "install and rerun the application";
        JOptionPane.showMessageDialog(this, msg, this.getTitle(), JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM