---
title: "servlet中调用数据库 "
author: "icsnowing"
date: "2008-06-30T09:36:17Z"
tags: []
slug: "servlet"
draft: false
lastmod: "2008-06-30T09:36:17Z"
id: 209599
url: "https://icsnowing.iteye.com/blog/209599"
---

web工程，目标平台部署到sailfin。sailfin平台中已经创建MySQL数据源。编写一个servlet，连接sailfin中的MySQL。
    举例：
    public class firstservlet extends HttpServlet
    {
        static Connection dbcon;
        public void doPost(HttpServletRequest req,
                           HttpServletResponse res)
            throws ServletException, IOException
        {
            try
            {
                Class.forName("com.mysql.jdbc.Driver");
                String dbURL = "jdbc:mysql://localhost:3306/test";  //JDBC数据源设置的url
                String username = "root";                           //JDBC数据源设置的用户名
                String password = "111111";                        //JDBC数据源设置的用户名
                dbcon = DriverManager.getConnection(dbURL, username, password);
                ……
            }
            catch(Exception e)
            {
                System.out.println("UNKNOWN!?");
                System.out.println(e.toString());
            }
            ……
            try
            {
                PreparedStatement s = dbcon.prepareStatement("select * from user where id=? and name=?");  //user为test下的表
                s.setString(1, accnum);
                s.setString(2, pinnum);
                ResultSet result = s.executeQuery();
            }
            catch(SQLException e)
            {
                System.out.println(e.toString());
            }
            ……
        }
    }