java 链接mysql
import java.sql.*; public class ConnectSql { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost:3306/mytest"; public static void main(String[] args) { Connection conn = null; Statement stme = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, "root", "root"); stme = conn.createStatement(); stme.execute("select * from websites"); ResultSet resultSet = stme.getResultSet(); while (resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); String url = resultSet.getString("url"); System.out.println(id); System.out.println(name); System.out.println(url); } resultSet.close(); stme.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } }
}
一般情况下不使用statem 使用PreparedStatement 防止注入攻击
InputStream in = MybaitsDemo.class.getClassLoader() .getResourceAsStream("mybaits-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); SqlSession session= sqlSessionFactory.openSession(); WebMapper mapper = session.getMapper(WebMapper.class); String url=mapper.selectAll(); System.out.println(url); session.close();
连接mybaits