根据表名获得字段名

根据表名获得字段名

//开发工具Eclipse3.2,SQLServer2000
 

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

/**/ /*
 *@author 我为J狂 建立日期 2007-5-4
 *
 
*/


public   class  MetaDataTest
{
    
public static void main(String[] args)
    
{
        System.out.println(
" 表mytable中的字段: " + getAllFields(" mytable ")); // 取出数据库db中的表mytable中的所有字段名
    }


    
public static String getAllFields(String myTable)
    
{
        Connection con 
= null;
        Statement st 
= null;
        ResultSet rs 
= null;
        String allFields 
= " ";
        String str 
= " ";
        java.sql.ResultSetMetaData rsm 
= null;
        
try
        
{
            Class.forName(
"com.microsoft.jdbc.sqlserver.SQLServerDriver");
            con 
= DriverManager
                    .getConnection(
                            
"jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db",
                            
"sa""");
            st 
= con.createStatement();
            rs 
= st.executeQuery("select * from " + myTable);
            rsm 
= rs.getMetaData();
            
int num = rsm.getColumnCount();
            
for (int i = 1; i <= num; i++)
            
{
                allFields 
= str + rsm.getColumnName(i) + " ";
                str 
= allFields;
            }

        }
 catch (Exception ex)
        
{
            ex.printStackTrace();
            
return "";
        }
 finally
        
{
            
if (rs != null)
            
{

                
try
                
{
                    rs.close();
                }
 catch (SQLException e)
                
{
                    
// TODO Auto-generated catch block
                    e.printStackTrace();
                }

                rs 
= null;
            }

            
if (st != null)
            
{

                
try
                
{
                    st.close();
                }
 catch (SQLException e)
                
{
                    
// TODO Auto-generated catch block
                    e.printStackTrace();
                }

                st 
= null;
            }

            
if (con != null)
            
{

                
try
                
{
                    con.close();
                }
 catch (SQLException e)
                
{
                    
// TODO Auto-generated catch block
                    e.printStackTrace();
                }

                con 
= null;
            }

        }

        
return allFields;
    }

}



你可能感兴趣的:(根据表名获得字段名)