SlideShare ist ein Scribd-Unternehmen logo
1 von 5
VISUALIZAR REGISTROS (BD. NORTHWIND) EN UN JTABLE (NETBEANS – SQL SERVER)<br />CONSULTA<br />select P.ProductID, <br />P.ProductName, <br />C.CategoryName, <br />S.CompanyName, <br />P.UnitPrice, <br />P.UnitsInStock, <br />P.QuantityPerUnit<br />from Products P inner join Categories C <br />on P.CategoryID = C.CategoryID <br /> inner join Suppliers S<br /> on P.SupplierID = S.SupplierID<br />ConnectionManager<br />package examen;<br />import java.sql.Connection;<br />import java.sql.DriverManager;<br />import java.sql.SQLException;<br />public class ConnectionManager {<br />    final private static String DRIVER = quot;
com.microsoft.sqlserver.jdbc.SQLServerDriverquot;
;<br />    final private static String URL = quot;
jdbc:sqlserver://localhost:1433;DatabaseName=Northwindquot;
;<br />    final private static String USER = quot;
saquot;
;<br />    final private static String PASSWORD = quot;
123quot;
;<br />    private static Connection cn = null;<br />    private ConnectionManager() {<br />    }<br />    public static Connection getConnection()<br />            throws ClassNotFoundException,<br />            SQLException,<br />            Exception {<br />        if (cn == null) {<br />            try {<br />                Class.forName(DRIVER).newInstance();<br />                cn = DriverManager.getConnection(URL, USER, PASSWORD);<br />            } catch (ClassNotFoundException ex) {<br />                throw ex;<br />            } catch (SQLException ex) {<br />                throw ex;<br />            } catch (Exception ex) {<br />                throw ex;<br />            }<br />        }<br />        return cn;<br />    }<br />}<br />Producto<br />package examen;<br />import java.io.Serializable;<br />public class Producto implements Serializable {<br />    private int ProductId;<br />    private String ProductName;<br />    private String CategoryName;<br />    private String CompanyName;<br />    private double UnitPrice;<br />    private int UnitStock;<br />    private String UnidadMedidad;<br />    public Producto() {<br />    }<br />    public Producto(int ProductId, String ProductName, String CategoryName, String CompanyName, double UnitPrice, int UnitStock, String UnidadMedidad) {<br />        this.ProductId = ProductId;<br />        this.ProductName = ProductName;<br />        this.CategoryName = CategoryName;<br />        this.CompanyName = CompanyName;<br />        this.UnitPrice = UnitPrice;<br />        this.UnitStock = UnitStock;<br />        this.UnidadMedidad = UnidadMedidad;<br />    }<br />    public String getCategoryName() {<br />        return CategoryName;<br />    }<br />    public void setCategoryName(String CategoryName) {<br />        this.CategoryName = CategoryName;<br />    }<br />    public String getCompanyName() {<br />        return CompanyName;<br />    }<br />    public void setCompanyName(String CompanyName) {<br />        this.CompanyName = CompanyName;<br />    }<br />    public int getProductId() {<br />        return ProductId;<br />    }<br />    public void setProductId(int ProductId) {<br />        this.ProductId = ProductId;<br />    }<br />    public String getProductName() {<br />        return ProductName;<br />    }<br />    public void setProductName(String ProductName) {<br />        this.ProductName = ProductName;<br />    }<br />    public String getUnidadMedidad() {<br />        return UnidadMedidad;<br />    }<br />    public void setUnidadMedidad(String UnidadMedidad) {<br />        this.UnidadMedidad = UnidadMedidad;<br />    }<br />    public double getUnitPrice() {<br />        return UnitPrice;<br />    }<br />    public void setUnitPrice(double UnitPrice) {<br />        this.UnitPrice = UnitPrice;<br />    }<br />    public int getUnitStock() {<br />        return UnitStock;<br />    }<br />    public void setUnitStock(int UnitStock) {<br />        this.UnitStock = UnitStock;<br />    }<br />}<br />ProductoDAO <br />package examen;<br />import java.sql.CallableStatement;<br />import java.sql.Connection;<br />import java.sql.PreparedStatement;<br />import java.sql.ResultSet;<br />import java.sql.SQLException;<br />import java.sql.Statement;<br />import java.util.ArrayList;<br />public class ProductoDAO {<br />    private Connection cn = null;<br />    private Statement st = null;<br />    private PreparedStatement ps = null;<br />    private CallableStatement cs = null;<br />    private ResultSet rs = null;<br />    public ArrayList<Producto> getProducto() {<br />        ArrayList<Producto> productos =<br />                new ArrayList<Producto>();<br />        final String QUERY = quot;
select p.ProductID , p.ProductName, C.CategoryName, s.CompanyName, p.UnitPrice, p.UnitsInStock, p.QuantityPerUnit from Products p inner join Categories c on p.CategoryID = C.CategoryID inner join Suppliers s  on p.SupplierID = s.SupplierID quot;
;<br />        try {<br />            cn = ConnectionManager.getConnection();<br />            st = cn.createStatement();<br />            rs = st.executeQuery(QUERY);<br />            while (rs.next()) {<br />                Producto c = new Producto(<br />                        rs.getInt(1),<br />                        rs.getString(2),<br />                        rs.getString(3),<br />                        rs.getString(4),<br />                        rs.getDouble(5),<br />                        rs.getInt(6),<br />                        rs.getString(7));<br />                productos.add(c);<br />            }<br />        } catch (SQLException ex) {<br />        } catch (Exception ex) {<br />        } finally {<br />            try {<br />                if (rs != null) {<br />                    rs.close();<br />                }<br />                if (st != null) {<br />                    st.close();<br />                }<br />                if (cn != null) {<br />                    cn.close();<br />                }<br />            } catch (Exception ex) {<br />            }<br />        }<br />        return productos;<br />    }<br />}<br />CODIGO FUENTE<br />package examen;<br />import java.util.ArrayList;<br />import java.util.Vector;<br />import javax.swing.table.DefaultTableModel;<br />import javax.swing.table.TableColumn;<br />public class FrmConsultaProductos extends javax.swing.JFrame {<br />    private DefaultTableModel dtm;<br />    public FrmConsultaProductos() {<br />        initComponents();<br />        configurartabla();<br />        cargartabla();<br />    }<br />public static void main(String args[]) {<br />        java.awt.EventQueue.invokeLater(new Runnable() {<br />            public void run() {<br />                new FrmConsultaProductos().setVisible(true);<br />            }<br />        });<br />    }<br />    // Variables declaration - do not modify                     <br />    private javax.swing.JScrollPane jScrollPane1;<br />    private javax.swing.JTable tblProducto;<br />    // End of variables declaration                   <br />    private void cargartabla() {<br />        ProductoDAO bo = new ProductoDAO();<br />        ArrayList<Producto> productos =<br />                bo.getProducto();<br />        dtm = (DefaultTableModel) tblProducto.getModel();<br />        for (Producto c : productos) {<br />            Vector fila = new Vector();<br />            fila.add(c.getProductId());<br />            fila.add(c.getProductName());<br />            fila.add(c.getCategoryName());<br />            fila.add(c.getCompanyName());<br />            fila.add(c.getUnitPrice());<br />            fila.add(c.getUnitStock());<br />            fila.add(c.getUnidadMedidad());<br />            dtm.addRow(fila);<br />        }<br />    }<br />    private void configurartabla() {<br />        TableColumn column = null;<br />        column = tblProducto.getColumnModel().getColumn(0);<br />        column.setPreferredWidth(2);<br />        column = tblProducto.getColumnModel().getColumn(1);<br />        column.setPreferredWidth(150);<br />        column = tblProducto.getColumnModel().getColumn(2);<br />        column.setPreferredWidth(150);<br />    }<br />}<br />
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE

Weitere ähnliche Inhalte

Was ist angesagt?

Create a Customized GMF DnD Framework
Create a Customized GMF DnD FrameworkCreate a Customized GMF DnD Framework
Create a Customized GMF DnD Framework
Kaniska Mandal
 
Rajeev oops 2nd march
Rajeev oops 2nd marchRajeev oops 2nd march
Rajeev oops 2nd march
Rajeev Sharan
 

Was ist angesagt? (19)

code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming hero
 
Ip project
Ip projectIp project
Ip project
 
Pre zen ta sion
Pre zen ta sionPre zen ta sion
Pre zen ta sion
 
Specs2
Specs2Specs2
Specs2
 
Rxjs vienna
Rxjs viennaRxjs vienna
Rxjs vienna
 
LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기
 
MaintainStaffTable
MaintainStaffTableMaintainStaffTable
MaintainStaffTable
 
Ip project visual mobile
Ip project visual mobileIp project visual mobile
Ip project visual mobile
 
The Ring programming language version 1.5.3 book - Part 44 of 184
The Ring programming language version 1.5.3 book - Part 44 of 184The Ring programming language version 1.5.3 book - Part 44 of 184
The Ring programming language version 1.5.3 book - Part 44 of 184
 
Create a Customized GMF DnD Framework
Create a Customized GMF DnD FrameworkCreate a Customized GMF DnD Framework
Create a Customized GMF DnD Framework
 
The Ring programming language version 1.7 book - Part 10 of 196
The Ring programming language version 1.7 book - Part 10 of 196The Ring programming language version 1.7 book - Part 10 of 196
The Ring programming language version 1.7 book - Part 10 of 196
 
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
 
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅
 
Jason parsing
Jason parsingJason parsing
Jason parsing
 
javascript function & closure
javascript function & closurejavascript function & closure
javascript function & closure
 
Rajeev oops 2nd march
Rajeev oops 2nd marchRajeev oops 2nd march
Rajeev oops 2nd march
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
 
Student management system
Student management systemStudent management system
Student management system
 

Ähnlich wie VISUALIZAR REGISTROS EN UN JTABLE

DAOFactory.javaDAOFactory.javapublicclassDAOFactory{ this .docx
DAOFactory.javaDAOFactory.javapublicclassDAOFactory{ this .docxDAOFactory.javaDAOFactory.javapublicclassDAOFactory{ this .docx
DAOFactory.javaDAOFactory.javapublicclassDAOFactory{ this .docx
theodorelove43763
 
database propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdf
database propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdfdatabase propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdf
database propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdf
fashiionbeutycare
 
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxsrcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
whitneyleman54422
 
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
honey725342
 

Ähnlich wie VISUALIZAR REGISTROS EN UN JTABLE (20)

AJUG April 2011 Cascading example
AJUG April 2011 Cascading exampleAJUG April 2011 Cascading example
AJUG April 2011 Cascading example
 
DAOFactory.javaDAOFactory.javapublicclassDAOFactory{ this .docx
DAOFactory.javaDAOFactory.javapublicclassDAOFactory{ this .docxDAOFactory.javaDAOFactory.javapublicclassDAOFactory{ this .docx
DAOFactory.javaDAOFactory.javapublicclassDAOFactory{ this .docx
 
database propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdf
database propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdfdatabase propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdf
database propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdf
 
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
CSharp v1.0.2
CSharp v1.0.2CSharp v1.0.2
CSharp v1.0.2
 
Easy Button
Easy ButtonEasy Button
Easy Button
 
Android Design Patterns
Android Design PatternsAndroid Design Patterns
Android Design Patterns
 
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxsrcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
 
Google guava
Google guavaGoogle guava
Google guava
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
 
Beautiful java script
Beautiful java scriptBeautiful java script
Beautiful java script
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
Guice2.0
Guice2.0Guice2.0
Guice2.0
 
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6
 
Greach, GroovyFx Workshop
Greach, GroovyFx WorkshopGreach, GroovyFx Workshop
Greach, GroovyFx Workshop
 
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
 

Mehr von Darwin Durand

EJEMPLOS DESARROLLADOS
EJEMPLOS DESARROLLADOSEJEMPLOS DESARROLLADOS
EJEMPLOS DESARROLLADOS
Darwin Durand
 
PERSISTENCIA BASADA EN ARCHIVOS
PERSISTENCIA BASADA EN ARCHIVOSPERSISTENCIA BASADA EN ARCHIVOS
PERSISTENCIA BASADA EN ARCHIVOS
Darwin Durand
 
PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)
PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)
PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)
Darwin Durand
 
CONEXION VISUAL STUDIO.NET - SQL SERVER
CONEXION VISUAL STUDIO.NET - SQL SERVERCONEXION VISUAL STUDIO.NET - SQL SERVER
CONEXION VISUAL STUDIO.NET - SQL SERVER
Darwin Durand
 
CREACION DE DLL Y USO (Ejemplo desarrollado)
CREACION DE DLL Y USO (Ejemplo desarrollado)CREACION DE DLL Y USO (Ejemplo desarrollado)
CREACION DE DLL Y USO (Ejemplo desarrollado)
Darwin Durand
 
CURSO DE PROGRAMACION AVANZADA EN JAVA EN ESPAÑOL
CURSO DE PROGRAMACION AVANZADA EN JAVA EN ESPAÑOLCURSO DE PROGRAMACION AVANZADA EN JAVA EN ESPAÑOL
CURSO DE PROGRAMACION AVANZADA EN JAVA EN ESPAÑOL
Darwin Durand
 
INDICES EN SQL SERVER
INDICES EN SQL SERVERINDICES EN SQL SERVER
INDICES EN SQL SERVER
Darwin Durand
 
APLICACIONES EMPRESARIALES
APLICACIONES EMPRESARIALESAPLICACIONES EMPRESARIALES
APLICACIONES EMPRESARIALES
Darwin Durand
 
CREACION Y MANEJO DE LA BASE DE DATOS
CREACION Y MANEJO DE LA BASE DE DATOSCREACION Y MANEJO DE LA BASE DE DATOS
CREACION Y MANEJO DE LA BASE DE DATOS
Darwin Durand
 

Mehr von Darwin Durand (13)

Ejemplos Borland C++ Builder
Ejemplos Borland C++ BuilderEjemplos Borland C++ Builder
Ejemplos Borland C++ Builder
 
EJEMPLOS DESARROLLADOS
EJEMPLOS DESARROLLADOSEJEMPLOS DESARROLLADOS
EJEMPLOS DESARROLLADOS
 
PERSISTENCIA BASADA EN ARCHIVOS
PERSISTENCIA BASADA EN ARCHIVOSPERSISTENCIA BASADA EN ARCHIVOS
PERSISTENCIA BASADA EN ARCHIVOS
 
PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)
PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)
PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)
 
CONEXION VISUAL STUDIO.NET - SQL SERVER
CONEXION VISUAL STUDIO.NET - SQL SERVERCONEXION VISUAL STUDIO.NET - SQL SERVER
CONEXION VISUAL STUDIO.NET - SQL SERVER
 
CREACION DE DLL Y USO (Ejemplo desarrollado)
CREACION DE DLL Y USO (Ejemplo desarrollado)CREACION DE DLL Y USO (Ejemplo desarrollado)
CREACION DE DLL Y USO (Ejemplo desarrollado)
 
CURSO DE PROGRAMACION AVANZADA EN JAVA EN ESPAÑOL
CURSO DE PROGRAMACION AVANZADA EN JAVA EN ESPAÑOLCURSO DE PROGRAMACION AVANZADA EN JAVA EN ESPAÑOL
CURSO DE PROGRAMACION AVANZADA EN JAVA EN ESPAÑOL
 
SERVLET BASICS
SERVLET BASICSSERVLET BASICS
SERVLET BASICS
 
INDICES EN SQL SERVER
INDICES EN SQL SERVERINDICES EN SQL SERVER
INDICES EN SQL SERVER
 
INTEGRIDAD DE DATOS
INTEGRIDAD DE DATOSINTEGRIDAD DE DATOS
INTEGRIDAD DE DATOS
 
APLICACIONES EMPRESARIALES
APLICACIONES EMPRESARIALESAPLICACIONES EMPRESARIALES
APLICACIONES EMPRESARIALES
 
CREACION Y MANEJO DE LA BASE DE DATOS
CREACION Y MANEJO DE LA BASE DE DATOSCREACION Y MANEJO DE LA BASE DE DATOS
CREACION Y MANEJO DE LA BASE DE DATOS
 
CREACION DE TABLAS
CREACION DE TABLASCREACION DE TABLAS
CREACION DE TABLAS
 

Kürzlich hochgeladen

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 

Kürzlich hochgeladen (20)

Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 

VISUALIZAR REGISTROS EN UN JTABLE

  • 1. VISUALIZAR REGISTROS (BD. NORTHWIND) EN UN JTABLE (NETBEANS – SQL SERVER)<br />CONSULTA<br />select P.ProductID, <br />P.ProductName, <br />C.CategoryName, <br />S.CompanyName, <br />P.UnitPrice, <br />P.UnitsInStock, <br />P.QuantityPerUnit<br />from Products P inner join Categories C <br />on P.CategoryID = C.CategoryID <br /> inner join Suppliers S<br /> on P.SupplierID = S.SupplierID<br />ConnectionManager<br />package examen;<br />import java.sql.Connection;<br />import java.sql.DriverManager;<br />import java.sql.SQLException;<br />public class ConnectionManager {<br /> final private static String DRIVER = quot; com.microsoft.sqlserver.jdbc.SQLServerDriverquot; ;<br /> final private static String URL = quot; jdbc:sqlserver://localhost:1433;DatabaseName=Northwindquot; ;<br /> final private static String USER = quot; saquot; ;<br /> final private static String PASSWORD = quot; 123quot; ;<br /> private static Connection cn = null;<br /> private ConnectionManager() {<br /> }<br /> public static Connection getConnection()<br /> throws ClassNotFoundException,<br /> SQLException,<br /> Exception {<br /> if (cn == null) {<br /> try {<br /> Class.forName(DRIVER).newInstance();<br /> cn = DriverManager.getConnection(URL, USER, PASSWORD);<br /> } catch (ClassNotFoundException ex) {<br /> throw ex;<br /> } catch (SQLException ex) {<br /> throw ex;<br /> } catch (Exception ex) {<br /> throw ex;<br /> }<br /> }<br /> return cn;<br /> }<br />}<br />Producto<br />package examen;<br />import java.io.Serializable;<br />public class Producto implements Serializable {<br /> private int ProductId;<br /> private String ProductName;<br /> private String CategoryName;<br /> private String CompanyName;<br /> private double UnitPrice;<br /> private int UnitStock;<br /> private String UnidadMedidad;<br /> public Producto() {<br /> }<br /> public Producto(int ProductId, String ProductName, String CategoryName, String CompanyName, double UnitPrice, int UnitStock, String UnidadMedidad) {<br /> this.ProductId = ProductId;<br /> this.ProductName = ProductName;<br /> this.CategoryName = CategoryName;<br /> this.CompanyName = CompanyName;<br /> this.UnitPrice = UnitPrice;<br /> this.UnitStock = UnitStock;<br /> this.UnidadMedidad = UnidadMedidad;<br /> }<br /> public String getCategoryName() {<br /> return CategoryName;<br /> }<br /> public void setCategoryName(String CategoryName) {<br /> this.CategoryName = CategoryName;<br /> }<br /> public String getCompanyName() {<br /> return CompanyName;<br /> }<br /> public void setCompanyName(String CompanyName) {<br /> this.CompanyName = CompanyName;<br /> }<br /> public int getProductId() {<br /> return ProductId;<br /> }<br /> public void setProductId(int ProductId) {<br /> this.ProductId = ProductId;<br /> }<br /> public String getProductName() {<br /> return ProductName;<br /> }<br /> public void setProductName(String ProductName) {<br /> this.ProductName = ProductName;<br /> }<br /> public String getUnidadMedidad() {<br /> return UnidadMedidad;<br /> }<br /> public void setUnidadMedidad(String UnidadMedidad) {<br /> this.UnidadMedidad = UnidadMedidad;<br /> }<br /> public double getUnitPrice() {<br /> return UnitPrice;<br /> }<br /> public void setUnitPrice(double UnitPrice) {<br /> this.UnitPrice = UnitPrice;<br /> }<br /> public int getUnitStock() {<br /> return UnitStock;<br /> }<br /> public void setUnitStock(int UnitStock) {<br /> this.UnitStock = UnitStock;<br /> }<br />}<br />ProductoDAO <br />package examen;<br />import java.sql.CallableStatement;<br />import java.sql.Connection;<br />import java.sql.PreparedStatement;<br />import java.sql.ResultSet;<br />import java.sql.SQLException;<br />import java.sql.Statement;<br />import java.util.ArrayList;<br />public class ProductoDAO {<br /> private Connection cn = null;<br /> private Statement st = null;<br /> private PreparedStatement ps = null;<br /> private CallableStatement cs = null;<br /> private ResultSet rs = null;<br /> public ArrayList<Producto> getProducto() {<br /> ArrayList<Producto> productos =<br /> new ArrayList<Producto>();<br /> final String QUERY = quot; select p.ProductID , p.ProductName, C.CategoryName, s.CompanyName, p.UnitPrice, p.UnitsInStock, p.QuantityPerUnit from Products p inner join Categories c on p.CategoryID = C.CategoryID inner join Suppliers s on p.SupplierID = s.SupplierID quot; ;<br /> try {<br /> cn = ConnectionManager.getConnection();<br /> st = cn.createStatement();<br /> rs = st.executeQuery(QUERY);<br /> while (rs.next()) {<br /> Producto c = new Producto(<br /> rs.getInt(1),<br /> rs.getString(2),<br /> rs.getString(3),<br /> rs.getString(4),<br /> rs.getDouble(5),<br /> rs.getInt(6),<br /> rs.getString(7));<br /> productos.add(c);<br /> }<br /> } catch (SQLException ex) {<br /> } catch (Exception ex) {<br /> } finally {<br /> try {<br /> if (rs != null) {<br /> rs.close();<br /> }<br /> if (st != null) {<br /> st.close();<br /> }<br /> if (cn != null) {<br /> cn.close();<br /> }<br /> } catch (Exception ex) {<br /> }<br /> }<br /> return productos;<br /> }<br />}<br />CODIGO FUENTE<br />package examen;<br />import java.util.ArrayList;<br />import java.util.Vector;<br />import javax.swing.table.DefaultTableModel;<br />import javax.swing.table.TableColumn;<br />public class FrmConsultaProductos extends javax.swing.JFrame {<br /> private DefaultTableModel dtm;<br /> public FrmConsultaProductos() {<br /> initComponents();<br /> configurartabla();<br /> cargartabla();<br /> }<br />public static void main(String args[]) {<br /> java.awt.EventQueue.invokeLater(new Runnable() {<br /> public void run() {<br /> new FrmConsultaProductos().setVisible(true);<br /> }<br /> });<br /> }<br /> // Variables declaration - do not modify <br /> private javax.swing.JScrollPane jScrollPane1;<br /> private javax.swing.JTable tblProducto;<br /> // End of variables declaration <br /> private void cargartabla() {<br /> ProductoDAO bo = new ProductoDAO();<br /> ArrayList<Producto> productos =<br /> bo.getProducto();<br /> dtm = (DefaultTableModel) tblProducto.getModel();<br /> for (Producto c : productos) {<br /> Vector fila = new Vector();<br /> fila.add(c.getProductId());<br /> fila.add(c.getProductName());<br /> fila.add(c.getCategoryName());<br /> fila.add(c.getCompanyName());<br /> fila.add(c.getUnitPrice());<br /> fila.add(c.getUnitStock());<br /> fila.add(c.getUnidadMedidad());<br /> dtm.addRow(fila);<br /> }<br /> }<br /> private void configurartabla() {<br /> TableColumn column = null;<br /> column = tblProducto.getColumnModel().getColumn(0);<br /> column.setPreferredWidth(2);<br /> column = tblProducto.getColumnModel().getColumn(1);<br /> column.setPreferredWidth(150);<br /> column = tblProducto.getColumnModel().getColumn(2);<br /> column.setPreferredWidth(150);<br /> }<br />}<br />