Home > Database > Mysql Tutorial > java连接mysql数据库实例_MySQL

java连接mysql数据库实例_MySQL

WBOY
Release: 2016-05-31 08:50:12
Original
887 people have browsed it

1、下载并添加mysql-connector-java-5.1.17-bin.jar包


2、代码

package mysqltest;import java.io.*;import java.sql.*;public class test { public static void main(String[] args) {  String JDriver= "com.mysql.jdbc.Driver";  String connectdb="jdbc:mysql://127.0.0.1:3306/abc";//abc是database name  try{   Class.forName(JDriver);  }catch(ClassNotFoundException ex){   ex.printStackTrace();   System.out.println("加载数据库引擎失败!");   System.exit(0);  }   System.out.println("数据库引擎加载成功!");   try{   String user="root";   String password="123456";   Connection con=DriverManager.getConnection(connectdb, user, password);   System.out.println("连接数据库成功!");   Statement stmt=con.createStatement();   System.out.println("查询/n开始读取数据");   ResultSet rs=stmt.executeQuery("SELECT * FROM users where id=1");   while(rs.next())   {    System.out.println(rs.getString("id")+"/t"+rs.getString("name"));      }      stmt.close();   con.close();  }catch(SQLException e){   e.printStackTrace();   System.exit(0);  } }}
Copy after login




source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template