java-一个简单的访问DB的main方法使用

代码资源:http://outofmemory.cn/code-snippet/1085/java-usage-JDBC-connection-MYSQL-database


package com.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestJDBC {

	/**
	 * 入口函数
	 * 
	 * @param arg
	 */
	public static void main(String arg[]) {
		try {
			Connection con = null; // 定义一个MYSQL链接对象
			Class.forName("com.mysql.jdbc.Driver").newInstance(); // MYSQL驱动
			con = DriverManager
					.getConnection(
							"jdbc:mysql://*/liveEpg?useUnicode=true&characterEncoding=UTF-8",
							"root", "*"); // 链接本地MYSQL

			Statement stmt; // 创建声明
			stmt = con.createStatement();

			// 查询数据并输出
			String selectSql = "SELECT othChannelId FROM channel_info";
			ResultSet selectRes = stmt.executeQuery(selectSql);
			while (selectRes.next()) { // 循环输出结果集
				String username = selectRes.getString("othChannelId");
				System.out.println("username:" + username);
			}

		} catch (Exception e) {
			System.out.print("MYSQL ERROR:" + e.getMessage());
		}
	}
}



  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的在线投票系统的Java代码,使用MySQL作为数据库: 首先,需要创建一个投票项目的实体类(VoteItem)和投票记录的实体类(VoteRecord): ``` public class VoteItem { private int id; private String name; private int count; // getter and setter methods } public class VoteRecord { private int id; private int itemId; private String voterIp; private Date voteTime; // getter and setter methods } ``` 接下来,需要创建一个MySQL数据库,并创建两张表:vote_item用于存储投票项目,vote_record用于存储投票记录。下面是两张表的建表语句: ``` CREATE TABLE vote_item ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(100) NOT NULL, count INT DEFAULT 0 ); CREATE TABLE vote_record ( id INT PRIMARY KEY AUTO_INCREMENT, item_id INT NOT NULL, voter_ip VARCHAR(50) NOT NULL, vote_time DATETIME NOT NULL ); ``` 然后,创建一个投票服务类(VoteService),实现投票功能: ``` public class VoteService { private static final String DB_URL = "jdbc:mysql://localhost:3306/vote"; private static final String DB_USER = "root"; private static final String DB_PASSWORD = "root"; private static final String INSERT_VOTE_RECORD_SQL = "INSERT INTO vote_record (item_id, voter_ip, vote_time) VALUES (?, ?, ?)"; private static final String UPDATE_VOTE_ITEM_SQL = "UPDATE vote_item SET count = count + 1 WHERE id = ?"; private static final String GET_ALL_VOTE_ITEMS_SQL = "SELECT * FROM vote_item"; private static final String GET_VOTE_ITEM_SQL = "SELECT * FROM vote_item WHERE id = ?"; private Connection conn; public VoteService() throws SQLException { conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); } public List<VoteItem> getAllVoteItems() throws SQLException { List<VoteItem> items = new ArrayList<>(); try (PreparedStatement ps = conn.prepareStatement(GET_ALL_VOTE_ITEMS_SQL)) { ResultSet rs = ps.executeQuery(); while (rs.next()) { VoteItem item = new VoteItem(); item.setId(rs.getInt("id")); item.setName(rs.getString("name")); item.setCount(rs.getInt("count")); items.add(item); } } return items; } public VoteItem getVoteItem(int id) throws SQLException { try (PreparedStatement ps = conn.prepareStatement(GET_VOTE_ITEM_SQL)) { ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if (rs.next()) { VoteItem item = new VoteItem(); item.setId(rs.getInt("id")); item.setName(rs.getString("name")); item.setCount(rs.getInt("count")); return item; } else { return null; } } } public void vote(int itemId, String voterIp) throws SQLException { Date voteTime = new Date(); try (PreparedStatement ps = conn.prepareStatement(INSERT_VOTE_RECORD_SQL)) { ps.setInt(1, itemId); ps.setString(2, voterIp); ps.setTimestamp(3, new Timestamp(voteTime.getTime())); ps.executeUpdate(); } try (PreparedStatement ps = conn.prepareStatement(UPDATE_VOTE_ITEM_SQL)) { ps.setInt(1, itemId); ps.executeUpdate(); } } } ``` 最后,创建一个投票应用程序(VoteApp),使用Spring Boot框架实现Web界面: ``` @RestController public class VoteApp { private VoteService voteService; @Autowired public VoteApp(VoteService voteService) { this.voteService = voteService; } @GetMapping("/vote") public ModelAndView vote() throws SQLException { List<VoteItem> items = voteService.getAllVoteItems(); ModelAndView mv = new ModelAndView("vote"); mv.addObject("items", items); return mv; } @PostMapping("/vote") public String doVote(@RequestParam int itemId, HttpServletRequest request) throws SQLException { String voterIp = request.getRemoteAddr(); voteService.vote(itemId, voterIp); return "success"; } @GetMapping("/vote/{id}") public ModelAndView voteItem(@PathVariable int id) throws SQLException { VoteItem item = voteService.getVoteItem(id); if (item == null) { return new ModelAndView("error"); } else { ModelAndView mv = new ModelAndView("vote_item"); mv.addObject("item", item); return mv; } } public static void main(String[] args) { SpringApplication.run(VoteApp.class, args); } } ``` 在resources/templates目录下创建vote.html和vote_item.html两个模板文件,分别用于显示所有投票项目和单个投票项目的投票结果。 最后,启动投票应用程序,访问http://localhost:8080/vote即可进行投票。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值