java连接mysql示例代码 (一)

2014-11-24 08:26:41 · 作者: · 浏览: 0

[java]
package com.qiyi.datatools;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import junit.framework.TestCase;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class TableVoHelper extends TestCase {

@Test
public void testOp() throws Exception {
pstmt = con.prepareStatement("delete from tableB");
pstmt.execute();
pstmt = con.prepareStatement("select * from tableA ");
rs = pstmt.executeQuery();
ArrayList tVoList = new ArrayList();
while (rs.next()) {
TableVo tVo = new TableVo();
tVo.setId(rs.getInt(1));
tVoList.add(tVo);
}

pstmt = con.prepareStatement("insert into tableB(id)values ( )");
for (TableVo tVo : tVoList) {
pstmt.setInt(1, tVo.getId());
pstmt.execute();
}

}

@Before
public void setUp() throws Exception {
String CLASSNAME = "com.mysql.jdbc.Driver";
String URL = "jdbc:mysql://localhost:3306/fiona";
String UNAME = "root";
String PWD = "root";
Class.forName(CLASSNAME);
con = DriverManager.getConnection(URL, UNAME, PWD);
}

@After
public void tearDown() throws Exception {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (con != null) {
con.close();
}
}

Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;

class TableVo {
public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

private int id;
}
}
package com.qiyi.datatools;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import junit.framework.TestCase;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class TableVoHelper extends TestCase {

@Test
public void testOp() throws Exception {
pstmt = con.prepareStatement("delete from tableB");
pstmt.execute();
pstmt = con.prepareStatement("select * from tableA ");
rs = pstmt.executeQuery();
ArrayList tVoList = new ArrayList();
while (rs.next()) {
TableVo tVo = new TableVo();
tVo.setId(rs.getInt(1));
tVoList.add(tVo);
}

pstmt = con.prepareStatement("insert into tableB(id)values ( )");
for (TableVo tVo : tVoList) {
pstmt.setInt(1, tVo.getId());
pstmt.execute();
}

}

@Before
public void setUp() throws Exception {
String CLASSNAME = "com.mysql.jdbc.Driver";
String URL = "jdbc:mysql://localhost:3306/fiona";
String UNAME = "root";
String PWD = "root";
Class.forName(CLASSNAME);
con = DriverManager.getConnection(URL, UNAME, PWD);
}

@After www.2cto.com
public void tearDown() throws Exception {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (con != null) {
con.close();
}
}

Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;

class TableVo {
public int getId() {
return id;
}

public void setId(int id) {
this.id = id;