先建一个工程,接着建一个类(类名自己起就可以),可以不用先建package,在建类(Class)的时候会提示让你输入包名,对应的包也就建好了。
向src中加入数据库驱动
百度云链接:https://pan.baidu.com/s/15hElm9SgyILdHeK2Xieg_A 密码:2lr9
下载后复制粘贴到src下即可,然后右击build path,点击Add to Build Path
如图建好了之后就需要编代码了,其中可以不加入相应的Tomcat,因为本代码没有使用Tomcat服务器。
就会生成相应的Libraries
代码注释已经很清晰了,import 倒入包会在提示错误时找到对应的包
其中jdbc:mysql://localhost:3306/ssm的ssm为数据库名称,useUnicode=true&characterEncoding=utf8为与数据库连接的字符集
package com.siliedu;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class jdbc {
public static void main(String args[]) {
//连接对象
Connection conn=null;
//查询对象
PreparedStatement ps=null;
//结果集对象
ResultSet rs=null;
try {
//加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//获取链接
conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf8","root", "yym199810");
//查询语句。
String sql="select * from user ";
//获取statement
ps=conn.prepareStatement(sql);
//ps.setString(1, "0"); //占位符
//查询输出结果
rs=ps.executeQuery();
while(rs.next()) {
System.out.println(rs.getString("id")+" "+rs.getString("username"));//遍历输出
}
}catch(Exception e) {
e.printStackTrace();
}
finally {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}