Java使用jdbc连接远程mysql实现数据查询

需要:eclipse工具,eclipse能访问了Android也相似

远程服务器IP

服务器安装MySQL,设置远程访问权限

jdbc导入eclipse工具

package me.bao;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;




import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSetMetaData;

public class Test3 {
    public static void main(String[] args) {
         Connection conn=null;
        //1. JDBC连接MYSQL的代码很标准。 
        String DRIVER="com.mysql.jdbc.Driver";
        String URL="jdbc:mysql://172.0.0.1:3306/user_login";
       String USER="root";
        String PASSWORD="124578";
      
            try {
                Class.forName(DRIVER);
            } catch (ClassNotFoundException e1) {
                // TODO 自动生成的 catch 块
                e1.printStackTrace();
            }// 动态加载类
            //2.获得数据库链接
            try {
                conn=DriverManager.getConnection(URL, USER, PASSWORD);
            } catch (SQLException e1) {
                // TODO 自动生成的 catch 块
                e1.printStackTrace();
            }            
            
            
            try {
                // mysql简单的查询语句。
                String sql = "select * from user where username = ? and password = ? ";

                if (conn != null){   // connection不为null表示与数据库建立了连接
                    PreparedStatement ps = (PreparedStatement) conn.prepareStatement(sql);
                    if (ps != null){
                        // 设置上面的sql语句中的?的值为name
                        ps.setString(1, "user" );
                        ps.setString(2, "12345");
                        // 执行sql查询语句并返回结果集
                        ResultSet rs = ps.executeQuery();// 返回有值就ture
                        if(rs.next()){
                            //有值
                            
                            System.out.print(rs.getString(1));
                            System.out.print(rs.getString(2));


                        }

                        conn.close();
                        ps.close();
                       
                    }else {
                        
                    }
                }else {
                   
                }
            }catch (Exception e){
                e.printStackTrace();
                System.out.print("error");
                
            }
          

    }     
}
原文地址:https://www.cnblogs.com/xfweb/p/13669206.html