java链接MySQL
1.首先安装MySQL,把bin目录添加到path 环境变量
2.修改 sql 登录名为123456.update mysql.user set authentication_string=password('123456') where user='root'
3.mysql 官网下载mysql-connector-java-5.1.44,项目属性build path->configure build path ->libraries ->Add external Jars添加 mysql-connector-java-5.1.44文件夹里面的mysql-connector-java-5.1.44-bin.jar组件
4.打开mysql 服务登录 ,展示数据库,添加表格
net start mysql
mysql -uroot -p123456
show databases
use abc
5连接代码
import java.sql.*;
public class MainDemo {
public static void main(String[] args){
try{
//调用Class.forName()方法加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
System.out.println("成功加载MySQL驱动!");
}catch(ClassNotFoundException e1){
System.out.println("找不到MySQL驱动!");
e1.printStackTrace();
}
String url="jdbc:mysql://localhost:3306/abc"; //JDBC的URL
Connection conn;
try {
conn = DriverManager.getConnection(url, "root","123456");
//创建一个Statement对象
Statement stmt = conn.createStatement(); //创建Statement对象
System.out.print("成功连接到数据库!");
String sql="select * from abcbiao1";
ResultSet rs=stmt.executeQuery(sql);
System.out.println("编号"+"\t"+"姓名"+"\t"+"年龄");
while(rs.next())
{
System.out.print(rs.getInt(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.println();
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException e){
System.out.println("连接不成功");
e.printStackTrace();
}
}
}