一般引用mysql-connector-java这个包。

package DBManager;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set; import MyClient.ArrivalCities;
import MyClient.LineInfos;
import MyClient.TrainLineInfo; public class DBHelper { private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/traininfo";
private static final String USERNAME = "root";
private static final String PASSWORD = "123abcd";
Connection conn = null;
ResultSet result = null;
PreparedStatement statement = null;
PreparedStatement stateInsert = null;
PreparedStatement stateUnlock = null; public Connection getConnection() {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
} public ResultSet executeQuery(String sql) {
conn = this.getConnection();
try {
statement = conn.prepareStatement(sql);
result = statement.executeQuery();
return result;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("query data failed");
}
return null;
} public ResultSet findTrainLinesByDate(String start_city, String date) {
String dateStr = dateToString(date);
ResultSet result = this.executeQuery("select name,start_time from "
+ "line_" + dateStr + "_info " + "where start_city='"
+ start_city + "' and date='" + date + "'");
return result;
} public ResultSet findArrivalCities(String city, String line) {
ResultSet result = this
.executeQuery("select distinct arrival_city from " + city
+ "_city_info where line_num='" + line + "'");
return result;
} public ArrivalCities getAllArrivalCities(String startCity, String date) {
ArrivalCities cities = new ArrivalCities();
Set<String> list = new HashSet<String>();
ResultSet lines = this.findTrainLinesByDate(startCity, date);
try {
while (lines.next()) {
ResultSet arrivals = this.findArrivalCities(startCity,
lines.getString("name"));
while (arrivals.next()) {
list.add(arrivals.getString("arrival_city"));
}
}
if (list.size() > 0) {
cities.setCities(list);
return cities;
}
return null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
} public LineInfos getAllLineInfos(String startCity, String arrivalCity,
String date) {
LineInfos lineinfos = new LineInfos();
ResultSet lines = this.findTrainLinesByDate(startCity, date);
if (lines != null) {
try {
while (lines.next()) {
String name = lines.getString("name");
ResultSet result = this.executeQuery("select price from "
+ startCity + "_city_info where arrival_city="
+ '"' + arrivalCity + '"' + " and line_num=" + '"'
+ name + '"');
if (result.next()) {
TrainLineInfo train = new TrainLineInfo(name,
result.getInt("price"),
lines.getLong("start_time"));
lineinfos.getList().add(train);
}
}
return lineinfos;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
} public ResultSet findNumOfSellSeats(String date, String line) {
String dateStr = dateToString(date);
ResultSet result = this.executeQuery("SELECT count(id) as num from "
+ line + "_" + dateStr + "_info where is_out=1");
return result;
} public String dateToString(String date) {
String[] result = date.split("-");
StringBuilder sb = new StringBuilder();
for (String ss : result) {
sb.append(ss);
}
return sb.toString();
} //购票,更新数据库信息
public void getBuyTicket(String dep_city,String arr_city, String date, String line){
String seat = getProperSeat(dep_city, line, date);
String sql = "update "; } public boolean executeDelete(String sql) {
conn = this.getConnection();
try {
statement = conn.prepareStatement(sql);
if (statement.executeUpdate() > 0) {
return true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("delete data failed");
e.printStackTrace();
}
return false;
} public boolean executeUpdate(String sql) {
conn = this.getConnection();
try {
statement = conn.prepareStatement(sql);
if (statement.executeUpdate() > 0) {
return true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("update data failed");
e.printStackTrace();
}
return false;
} public boolean executeInsert(String sql, String date, String line) {
conn = this.getConnection();
String lockSql = "lock tables " + line + "_" + date + "_info write";
String unlockSql = "unlock tables";
try {
stateInsert = conn.prepareStatement(lockSql);
statement = conn.prepareStatement(sql);
stateUnlock = conn.prepareStatement(unlockSql);
stateInsert.executeQuery();
if (statement.executeUpdate() > 0) {
stateUnlock.executeQuery();
return true;
}
stateUnlock.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("insert data failed");
e.printStackTrace();
}
return false;
} }

java之操作mysql常用方法的更多相关文章

  1. java JDBC操作MySQL数据库

    一,首先在MYSQL建立一个数据库,例如Geek99DB: create database Geek99DB; use Geek99DB; 然后建立一个表CustomerTab: create tab ...

  2. 在Myeclipse中用Java语言操作mysql数据库

    package OperateMysql; import java.sql.*; public class MysqlTest { public static void main(String[] a ...

  3. 【Java】操作mysql数据库

    package bd; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; im ...

  4. Java -- JDBC 操作mysql数据库

    1. Demo1 导包时 不要导具体的mysql包, 为了兼容性,导JDBC 中 sql的包既可以了. public class Demo1 { /** * @param args * @throws ...

  5. Java 操作MySql数据库

    Java 项目开发中数据库操作是很重要的一个方面,对于初学者来说,MySql是比较容易熟悉的一种常见数据库,这篇文章记录了如何用Java来操作MySql数据库. 第一章 JDBC的概念 JDBC(Ja ...

  6. java分享第十七天-03(封装操作mysql类)

     JAVA操作mysql所需jar包:mysql-connector-java.jar代码: import java.sql.*; import java.util.ArrayList; import ...

  7. Java使用Jdbc操作MySql数据库(一)

    这个示例是Java操作MySql的基本方法. 在这个示例之前,要安装好MySql,并且配置好账户密码,创建一个logininfo数据库,在数据库中创建userinfo数据表.并且在表中添加示例数据. ...

  8. Java框架spring Boot学习笔记(五):Spring Boot操作MySQL数据库增、删、改、查

    在pom.xml添加一下代码,添加操作MySQL的依赖jar包. <dependency> <groupId>org.springframework.boot</grou ...

  9. Java框架spring Boot学习笔记(四):Spring Boot操作MySQL数据库

    在pom.xml添加一下代码,添加操作MySQL的依赖jar包. <dependency> <groupId>org.springframework.boot</grou ...

随机推荐

  1. 04->python字典

    字典dict 1.数据类型分类(按可变和不可变)     不可变数据类型:数字.bool.str.tuple     可变数据类型:list.dict.set 2.dict的组成     key:va ...

  2. springboot整合activemq(三)配置文件

    application.properties文件配置: #服务端口,8080被另一服务占用server.port=9090spring.activemq.broker-url=tcp://127.0. ...

  3. Infiniband交换机的FabricMonitor加载数据hang

    刚刚帮客户将Exadata中Infiniband交换机的固件版本从2.1.3-1 升级到2.2.7-1,但升级后发现Infiniband交换机的FabricMonitor功能无法使用,具体如下图所示. ...

  4. Qt 学习之路 2(9):资源文件

    Qt 学习之路 2(9):资源文件  豆子  2012年8月31日  Qt 学习之路 2  62条评论 上一章节中我们介绍了如何使用QAction添加动作.其中,我们使用QIcon加载了一张 png ...

  5. VC对话框的菜单设置变灰, 打勾 等

    一般可以用UPDATE_COMMAND_UI消息,并加入以下代码:pCmdUI->Enable(FALSE); 就实现,弹对话框的菜单需要增加对WM_INITMENUPOPUP消息的处理以后,才 ...

  6. cs231n学习笔记(二)图像分类

    图像分类可说是计算机视觉中的基础任务同时也是核心任务,做好分类可为检测,分割等高阶任务打好基础. 本节课主要讲了两个内容,K近邻和线性分类器,都是以猫的分类为例. 一. K近邻 以猫的分类为例,一张含 ...

  7. 【笔记】Pandas分类数据详解

    [笔记]Pandas分类数据详解 Pandas  Pandas分类数据详解|轻松玩转Pandas(5) 参考:Pandas分类数据详解|轻松玩转Pandas(5)

  8. Kibana6.x.x——启动后警告信息:Session cookies will be transmitted over insecure connections. This is not recommended.

    启动Kibana后,如果你看到如下警告信息: server log [08:03:18.001] [warning][security] Session cookies will be transmi ...

  9. Codeforces Round #305 (Div. 2) A

    Description While Mike was walking in the subway, all the stuff in his back-bag dropped on the groun ...

  10. rest_framework 的验证,权限,频率

    回到顶部 快速实例 Quickstart 回到顶部 序列化 创建一个序列化类 简单使用 开发我们的Web API的第一件事是为我们的Web API提供一种将代码片段实例序列化和反序列化为诸如json之 ...