请简述Java中如何使用JDBC连接数据库

 我来答
百度网友b1fa122
推荐于2017-10-01 · TA获得超过893个赞
知道大有可为答主
回答量:1059
采纳率:100%
帮助的人:1001万
展开全部
import java.sql.*;  
public class MysqlTest {  
    public static void main(String[] args){  
               // 驱动程序名        
        String driver = "com.mysql.jdbc.Driver";  
               // URL指向要访问的数据库名world        
        String url = "jdbc:mysql://127.0.0.1:3306/world";  
               // MySQL配置时的用户名           
        String user = "root";           
        // MySQL配置时的密码          
        String password = "123456";  
        String name;  
                try {               
                 // 加载驱动程序        
                Class.forName(driver);  
                    // 连续数据库       
               Connection conn = DriverManager.getConnection(url, user, password);  
                   if(!conn.isClosed())          
                  System.out.println("Succeeded connecting to the Database!");  
                  // statement用来执行SQL语句             
                     Statement statement = conn.createStatement();  
                 // 要执行的SQL语句           
                   String sql = "select * from city";  
                // 结果集       
                  ResultSet rs = statement.executeQuery(sql);  
                while(rs.next())  {         
               // 选择Name这列数据     
               name = rs.getString("Name");  
                  // 输出结果              
                  System.out.println(rs.getString("CountryCode") + "\t" + name);           
             }  
         rs.close();       conn.close();  }   
        catch(ClassNotFoundException e) {  
         System.out.println("Sorry,can`t find the Driver!");              
         e.printStackTrace();  
        } catch(SQLException e) {  
         e.printStackTrace();  
        } catch(Exception e) {  
         e.printStackTrace();  
        }   
        }  
}
匿名用户
2016-11-27
展开全部
JDK 的 API 文档中,java.sql.*

~
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式