在Java和mysql之间建立连接时出错

时间:2020-04-16 16:18:45

标签: java mysql

以下是我的代码....

import java.sql.*;
public class ConnectionTry {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try
        {
            System.out.println(1);
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println(2);
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/Test","root","password");
            if(!conn.isClosed())
            {
                System.out.println("connected");
            }
            System.out.println(3);
            PreparedStatement ps = conn.prepareStatement("insert into User(user_id,user_name,email,password) values (?,?,?,?);");
            System.out.println(4);      
            ps.setInt(1, 45);
            System.out.println(5);
            ps.setString(2, "@Suraj");
            ps.setString(3, "esuraj@gmail.com");
            ps.setString(4, "qwer1234");
            int x = ps.executeUpdate();
            if(x > 0) {
                System.out.println("Registration Successful");
            }
            else {
                System.out.println("Registration not Successful");
            }
        }
        catch(Exception c) {
            System.out.println(c.getMessage());
        }

    }

}

在上面的代码中: 测试是数据库, root 是mysql中的用户, 密码是mysql密码。

运行上面的代码时发生以下错误。

Unknown initial character set index '255' received from server. Initial client character set can be forced via the 'characterEncoding' property.

3 个答案:

答案 0 :(得分:0)

尝试设置字符编码,就像错误告诉您要这样做一样。

jdbc:mysql://localhost/Test?characterEncoding=utf8

答案 1 :(得分:-1)

您没有在URL数据库连接上指定端口,默认情况下为3306,并且您的url应该看起来像这样jdbc:mysql:// localhost:3306 / Test

答案 2 :(得分:-1)

此核心jdbc文件


import java.sql.*;

public class jdbcInsertTable {

    public static void insertvalue() throws SQLException{

        try {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("Connecting to a selected database...");

            Connection con= DriverManager.getConnection
                    ("jdbc:mysql://localhost:3306/oracl","root","root");
            System.out.println("Connected database successfully...");

            Statement stmt = con.createStatement();
            stmt.executeUpdate("insert into employee values('sagar','sales')");
            System.out.println("values insert successfully");

            con.close();

        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            System.out.println(e);
        }

    }
    public static void main(String[] args) throws SQLException {
        // TODO Auto-generated method stub

        insertvalue();
    }

}