import java.sql.*
public class TestMysql {
public static void main(String[] args) {
Connection conn = null
Statement stmt = null
ResultSet rs = null
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver")
//创建连接
conn = DriverManager
.getConnection("jdbc:mysql://localhost/bbs?user=用户名&password=密码")
stmt = conn.createStatement()
rs = stmt.executeQuery("select * from user")
while (rs.next()) {
String user = rs.getString(1)
String password = rs.getString(2)
System.out.println("用户名:" + user + "," +" 密码:" + password )
}
} catch (ClassNotFoundException ex) {
ex.printStackTrace()
} catch (SQLException ex) {
ex.printStackTrace()
} finally {
try {
if (rs != null) {
rs.close()
rs = null
}
if (stmt != null) {
stmt.close()
stmt = null
}
if (conn != null) {
conn.close()
conn = null
}
} catch (SQLException e) {
e.printStackTrace()
}
}
}
}
当然前提是要把MySQL的连接驱动JAR文件添加到工程里
java向数据库中插入数据,可以使用mysql数据库,使用statement类来 *** 作数据库,示例如下:
Connection conn = nullStatement st = null
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")//加载驱动类
conn = DriverManager.getConnection("jdbc:microsoft:sqlserver://<server_name>:<1433>", "name","pwd")
conn.setAutoCommit(false)
st = conn.createStatement()
// 模拟一个 str[i] = nd.getNodeValue().trim()
String[] str = new String[] { "aaa", "bbb", "ccc", "ddd", "eee","fff" }
String sqlStr = null
for (int i = 0 i < str.length i++) {
sqlStr = "INSERT INTO <TABLENAME> (<COLNAME>)VALUES('" + str[i] + "')"//向数据库中插入数据
st.executeUpdate(sqlStr)
}
conn.commit()
} catch (Exception e) {
e.printStackTrace()
} finally {//释放数据库的资源
try {
if (st != null)
st.close()
if(conn != null && !conn.isClosed()){
conn.close()
}
} catch (SQLException e) {
e.printStackTrace()
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)