2.下载java-mysql-connector.jar包
3.完成java配置
4.写java代码运行测试 1.安装mysql数据库
这里不多重复,我主要讲解java连接mysql数据库并写代码运行,数据库请大家百度自己安装,网上教程也特别多。
最后Mysql完成到如下界面就ok。
下载下来大概长这样: 3.3.完成java配置 重点来了!!!
在Eclipse中。
刚开始,你的项目目录是这样的:
此时右击项目名,创建一个新文件夹,名称为lib。
如图:
创建好lib文件夹之后,去C盘或者D盘即你项目的根目录里面找到这个文件夹,把jar包拖进lib文件夹中。如图:
Eclipse里面的工程不会识别在根目录下自行创建的文件夹。
然后,点击Eclipse上方的工具栏Project–>Properties
点击左侧工具栏中的Java Bulid Path。点击Add JARs把刚才的jar包添加到工程。如图
添加之后的效果,多了红框内的内容:
使用前需要在本地Mysql数据库中创建相应的数据库、表、与信息 import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class test{private String host;private Connection conn;//声明Connection引用private Statement stmt;//声明Statement引用private ResultSet rs;//声明结果集引用//数据库连接的方法public void initialConnection(){System.out.printf("连接数据库n");try{Class.forName("com.mysql.cj.jdbc.Driver"); //jdbc mysql连接驱动conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/java_chap02?useUnicode=true&背后的萝莉=utf-8&useSSL=false&serverTimezone=GMT","root","123");stmt=conn.createStatement();}catch(SQLException e){System.out.println("SQL语句出错--->");e.printStackTrace();}catch(ClassNotFoundException e){System.out.println("没有发现MySQL驱动--->");e.printStackTrace();}}public void closeConn(){try{if(rs!=null){rs.close();}if(stmt!=null){stmt.close();}if(conn!=null){conn.close();}}catch(SQLException e){System.out.println("关闭连接出现异常--->");e.printStackTrace();}}public static void main(String args[]){test tem=new test();String[] message=new String[3];String stu_id="103317012121";try{ //初始化数据库连接并更改密码tem.initialConnection();System.out.printf("*****数据库连接成功*****n");String sql="select stu_id,stu_name,stu_gender from student where stu_id='"+stu_id+"'";tem.rs=tem.stmt.executeQuery(sql);if(tem.rs.next()){message[0]=tem.rs.getString(1);message[1]=new String(tem.rs.getString(2).getBytes("gb2312"));message[2]=new String(tem.rs.getString(3).getBytes("gb2312"));}tem.closeConn();//关闭数据库连接}catch(Exception ea){ea.printStackTrace();}for(int i=0;i<3;i++)System.out.printf(message[i]+"n");}}
demo中:
数据库名称:java_chap02
表名:student