java连接mysql的一个小例子

想要用java 连接数据库,需要在classpath中加上jdbc的jar包路径

在eclipse中,Project的properties里面的java build path里面添加引用

连接成功的一个小例子
数据库如下如

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKEAAABaCAIAAABfZqE7AAAF+ElEQVR4nO2cTU8bRxjHn3M/Qj8BzZmuwKqqcIXv0KSWWJEP0FMPkQKFgCXiUyWaSyL1QBKlCWlwFSA9lNLIKiKKSUNgJy0kvDSxccjiF2gTbw72zs56Xw3e2fHo+el/2Mw+sxr5l10sz6OFR/vLzhy0yNTUVF9f3xe+nD17dmpqqtUrt51vlz+hGX786b0X32wX1r2KV8YUUMZWmodvnbcGV8YUtsL5z/O3bDOhjm2UPUdnr4wpjVq3JXijaVrTCLTFcQdRt5t68tmvW5P54m7cy2k/6Pjg+6dfZrd/fHuwH/dCogIdyw86lh90LD8uji/efE5z+edn17KrS3l0LBXwulyh0fKHPy3vXv19Ne5VIe0E/j7QaTb1w229fOn2WtyrQtoJvHirs/m3XLl48zk9bQRBCAmsiQhCyKuq0XHh/4mBVtTZ7JXQsXSO1/d1NjuH6Fg6x2sFnc2Ojo6lc/z0jc7m5Tt0LJ3jJ691NpsHJ3WsXemF3ita0/mM6jLYHtBxSODxns7mnxM7dgcdC+B4eVdnQ4o2x9Wj//xDCPEtuJeEnom/Ai5yshBCHu4bHZcYHGe3dTbavs1xpXrsH0KIeTyTBGV89bhSPa6spur728pEyhpsdxjHmQHovTCi1nfUz4xo9fHRc+Ym+7mMVXbjyhkAABi4YVwf6W2a8vDPxlkAdVQax49e6Ww2Cqd3PJMESN49rlSPcxMKROl4oVBbKNQWCrMDAPDV7EKhtjA9CDA42hinZ3suZM2y7snrjTI4M7xhn0IrawvTg42z7U4Mjpe2dDbP86d2vJpSlFTOeXNH69h0Y/dk3sjUsVsZPc5OmjcxAP1PI4HjxS2dzTO743LlyD+EEPN4JgnKeO6onEspSirXNBh0nROEEDKfr83na/P52X7oGcraj7OTXTD4Xb42n98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HHcsPOpYfdCw/6Fh+0LH8oGP5Qcfyg47lBx3LDzqWn48mz3GoPtVypAAAAABJRU5ErkJggg==" alt="" />

代码
package query;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public class query {
public static void main(String[] args) {
// 驱动程序名
String driver = "com.mysql.jdbc.Driver"; // URL指向要访问的数据库名9million
String url = "jdbc:mysql://127.0.0.1:3306/9million"; // MySQL配置时的用户名
String user = "root"; // MySQL配置时的密码
String password = ""; 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 testdata"; // 结果集
ResultSet rs = statement.executeQuery(sql); System.out.println("-----------------");
System.out.println("执行结果如下所示:");
System.out.println("-----------------");
System.out.println(" 学号" + "\t" + " 姓名");
System.out.println("-----------------"); String name = null; while (rs.next()) { // 选择sname这列数据
name = rs.getString("name"); // 首先使用ISO-8859-1字符集将name解码为字节序列并将结果存储新的字节数组中。
// 然后使用GB2312字符集解码指定的字节数组
name = new String(name.getBytes("ISO-8859-1"), "GB2312"); // 输出结果
System.out.println(rs.getString("id") + "\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(); } } }
上一篇:javascript小实例,移动端页面中的拖拽


下一篇:elasticsearch的索引操作和文档操作总结